专注于页面无法正常工作

问题描述:

如果存在CSS类,我将尝试着重于页面中的特定ID.但是我拥有的代码不起作用,我不确定为什么吗?

I am trying to set focus on a certain ID in the page if a CSS class is present. However the code that I have doesn't work and I am not certain why?

$(document).ready(function() {
    if ($('body').hasClass('message')) {
        $('#maincontent').focus();
    }
});

HTML: 页面中用于设置焦点的锚点:

HTML: The Anchor in the page to set focus:

<a name="maincontent" tabindex="-1" id="maincontent"/>

如果该div存在于页面中:

If this div is present in page:

<div class="message success"><p><span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span> Your submission has been received.</p></div>

将其更改为:

$(document).ready(function() {
    if ($('body .message').length) {
        $('#maincontent').focus();
    }
});

正文在HTML中没有类消息.

The body doesn't have class message in your HTML.