开发者

jQuery addClass to a tag problem

开发者 https://www.devze.com 2022-12-16 15:13 出处:网络
I have this in my html code: <ul id=\"navlist\" <li id=\"tabItem1\"><a href=\"#\">Item one</a></li>

I have this in my html code:

<ul id="navlist"
<li id="tabItem1"><a href="#">Item one</a></li>
<li id="tabItem2"><a 开发者_C百科href="#">Item two</a></li>
<li id="tabItem3"><a href="#">Item three</a></li>
<li id="tabItem4"><a href="#">Item four</a></li>
</ul>

I want to add a class to the a element with jquery like this: (its not working)

var currentTab = 1;

$(document).ready(function()
{        
  $("li#tabItem" + currentTab + ":has(a)").addClass("navlistHover");
  //console.log("li#tabItem" + currentTab + ":has(a)");
});

When a delete the a element and do it like the next example, than there is no problem.

$("li#tabItem" + currentTab).addClass("navlistHover");

I've tried the following code:

$('navlist li#tabItem' + currentTab + ' a').addClass('navlistHover');

but it's not working, very strange


Try this:

$('navlist li#tabItem' + currentTab + ' a').addClass('navlistHover');

The :has() selector selects items that have the a element as children:

http://docs.jquery.com/Selectors/has


It's working if you add the html closing tag for

<ul id="navlist">

0

精彩评论

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

关注公众号