jQuery Function Problem (Parent/Child)
I have a small problem with a jQuery script I wrote.
I have an HTML structure like this:
<div id="navigation">
<ul>
<li><a href="Link1"><b>Text1</b></a></li>
<li><a href="Link2"><b>Text2</b></a></li>
...
</ul>
</div>
Then, I have a click function binded to those li/a tabs that sets the value of the current page to href:
var currentpage = $(this).attr('href');
And, finally, an update function that is fired when it's needed that do many thing, but also changes the style of the currently selected li/a tab:
$('#navigation a').each(function()
{
var tab = $(this);
tab.parent().toggleClass('current', (tab.attr('href') == currentpage));
});
Everything work开发者_如何学编程s fine, but today I was trying to rewrite the last function on one line only -without calling each()- and I can't get it to work. I've tried many solutions like:
$('#navigation a').parent().toggleClass('current', ($(this).children(':first').attr('href') === currentpage));
$('#navigation a').parent().toggleClass('current', ($(':only-child', $(this)).attr('href') == currentpage));
Can someone help me out? Thanks!
You can't rewrite it as you'd like to.
The original code has to use ".each()" because it needs access to each individual <a>
element in order to do its thing. In your rewrite, you're imagining that you can get this
set to each element being processed, but that's just not how this
works in JavaScript. In your attempted rewrite, the value of this
in those parameters to "toggleClass()" will be this
as it stands outside that entire jQuery function call chain. It'll have absolutely nothing to do with the <a>
elements being processed by the call to "toggleClass()".
when your function is triggers i.e. on clicking the in that function you can get the reference to the clicked element, tag by using $(this). Then your code should be
$(this).parent().toggleClass('current', ($(this).children(':first').attr('href') === currentpage));
精彩评论