使用 Jquery 的类名将焦点设置为链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2380909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:22:36  来源:igfitidea点击:

Setting Focus to a link using class name with Jquery

jqueryhtmlcss

提问by VikingGoat

Using jQuery I am trying to set focus for (CSS purposes) to a particular link from a list of related links on the load of the page based upon the class name.

使用 jQuery,我试图将焦点(CSS 目的)设置为基于类名的页面加载相关链接列表中的特定链接。

Example, of the following I want to set focus to Link1

例如,以下我想将焦点设置为 Link1

<a href="#Link1" class="nav-button-left">Link1</a>
<a href="#Link2" class="nav-button">Link2</a>
<a href="#Link3" class="nav-button">Link3</a>
<a href="#Link4" class="nav-button">Link4</a>
<a href="#Link5" class="nav-button">Link5</a>
<a href="#Link6" class="nav-button-right">Link6</a>

Currently this is the code snippet I have working so far, and by working I mean I've set it up, it does nothing noticeable so far.

目前,这是我迄今为止工作的代码片段,通过工作我的意思是我已经设置了它,到目前为止它没有任何明显的作用。

<script type="text/JavaScript">
    $(window).load(function(){
        if($(this).attr("class") == 'nav-button-left'){$(".nav-button-left").focus();}  
    })
</script>

I'm fairly sure its the actual focus portion that's not working, although I can't fathom.

我相当确定它的实际焦点部分不起作用,尽管我无法理解。

回答by Nick Craver

You can just call .focus(), you don't need the if:

你可以打电话.focus(),你不需要if

$(".nav-button-left").focus();

In this code: if($(this).attr("class") == 'nav-button-left'){the reference thishas the window context, so it's evaluating false since the window doesn't have that class.

在此代码中: if($(this).attr("class") == 'nav-button-left'){引用this具有窗口上下文,因此它的值为 false,因为窗口没有该类。

If what you're trying to do is only call it if the element exists, you're set. In the above code, if the element isn't found then .focus()just won't be called since the selector didn't find anything.

如果您要做的只是在元素存在时调用它,那么您就设置好了。在上面的代码中,如果没有找到元素,则.focus()不会被调用,因为选择器没有找到任何东西。

Also, unless you need stuff to load like images before this executes, just use this call:

此外,除非您需要在执行之前加载类似图像的内容,否则只需使用以下调用:

$(function() { //equivalent to document.ready
  $(".nav-button-left").focus();
});

回答by Randall

Maybe use

也许用

$(this).hasClass(".nav-button-left")

$(this).hasClass(".nav-button-left")

rather than

而不是

$(this).attr("class") == 'nav-button-left'

$(this).attr("class") == 'nav-button-left'