不是专家,所以我试图理解为什么这种情况失败了。如果页面中存在css类,我希望它将焦点放在.alert-focus上,否则如果不是,则应将焦点设置在#maincontent上。但是它永远不会将焦点放在#maincontent上。
这是我的代码:
$(function() {
if ($('body .alert, body .success, body .warning').length) {
$('.alert-focus').focus();
} else {
$('#maincontent').focus();
}
});
<a id="maincontent" tabindex="-1" name="maincontent"></a>
答案 0 :(得分:0)
只要显示<a>
元素中有一些内容,您的代码就会有效。
下面的示例通过添加一个CSS规则来显示这一点,该规则仅在焦点有效时才适用于maincontent
。
$(function() {
if ($('body .alert, body .success, body .warning').length) {
$('.alert-focus').focus();
} else {
$('#maincontent').focus();
}
});
/* If you see a yellow background, the element has the focus! */
#maincontent:focus { background-color:yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- If an element doesn't have any content, then there's nothing to see.
You have to give the element something to be marked up. -->
<a id="maincontent" tabindex="-1" name="maincontent">test</a>