jQuery 函数问题(父/子)
我编写的 jQuery 脚本有一个小问题。
我有一个像这样的 HTML 结构:
<div id="navigation">
<ul>
<li><a href="Link1"><b>Text1</b></a></li>
<li><a href="Link2"><b>Text2</b></a></li>
...
</ul>
</div>
然后,我有一个绑定到那些 li/a 选项卡的单击函数,该函数将当前页面的值设置为 href:
var currentpage = $(this).attr('href');
最后,一个更新函数在需要时触发,可以做很多事情,但也更改了当前选定的 li/a 选项卡的样式:
$('#navigation a').each(function()
{
var tab = $(this);
tab.parent().toggleClass('current', (tab.attr('href') == currentpage));
});
一切正常,但今天我试图仅在一行上重写最后一个函数 - 不调用each() - 但我无法让它工作。 我尝试了很多解决方案,例如:
$('#navigation a').parent().toggleClass('current', ($(this).children(':first').attr('href') === currentpage));
$('#navigation a').parent().toggleClass('current', ($(':only-child', $(this)).attr('href') == currentpage));
有人可以帮助我吗? 谢谢!
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 works 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法按照自己的意愿重写它。
原始代码必须使用“.each()”,因为它需要访问每个单独的
元素才能完成其任务。在重写中,您想象可以将
this
设置为正在处理的每个元素,但这并不是this
在 JavaScript 中的工作方式。在您尝试重写时,“toggleClass()”参数中的this
值将是this
,因为它位于整个 jQuery 函数的外部调用链。它与调用“toggleClass()”处理的元素完全无关。
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 getthis
set to each element being processed, but that's just not howthis
works in JavaScript. In your attempted rewrite, the value ofthis
in those parameters to "toggleClass()" will bethis
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()".当您的函数被触发时,即单击该函数中的 时,您可以使用 $(this) 获取对单击的元素、标记的引用。那么你的代码应该是
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