开发者

Setting Focus to a link using class name with Jquery

开发者 https://www.devze.com 2022-12-21 19:15 出处:网络
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.

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.

Example, of the following I want to set focus to 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 开发者_JAVA百科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.


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

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

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

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.

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();
});


Maybe use

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

rather than

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

0

精彩评论

暂无评论...
验证码 换一张
取 消