Jquery 访问远程父母
考虑下拉菜单的以下 HTML 结构:
<ul class="tabMenu">
<li><a href="#">Games</a>
<div id="sub">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">3D</a></li>
</ul>
</div>
</li>
<li><a href="#">Videos</a>
<div id="sub">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">3D</a></li>
</ul>
</div>
</li>
</ul>
在此菜单下,我使用 Jquery 编写一些字符串(Home 是默认值),它告诉用户他在哪里:
<div class="Pointer"><a href="#">Home</a></div>
以下 Jquery 用于检测触发了哪个类别/子类别
$('.tabMenu li a').click(function() {
//get current link
var currentLink = $(this);
//get link text
var linkText = currentLink.text();
//Remove all activeTab classes
$('.activeTab').removeClass('activeTab');
//Add selected class with activeTab
currentLink.parent().addClass("activeTab");
//Change pointer value according to the click
$('.Pointer a').html(linkText);
});
:如果用户从“视频”下拉列表中单击子类别“Main”,Jquery 函数应返回类似“Videos->Main”的字符串;如果用户从“Games”中选择“Main”,则返回“Games->Main”。无论是从“游戏”还是“视频”中单击,此代码都仅提供 Main 任何帮助将不胜感激。
Consider the following HTML structure for drop-down menu:
<ul class="tabMenu">
<li><a href="#">Games</a>
<div id="sub">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">3D</a></li>
</ul>
</div>
</li>
<li><a href="#">Videos</a>
<div id="sub">
<ul>
<li><a href="#">Main</a></li>
<li><a href="#">3D</a></li>
</ul>
</div>
</li>
</ul>
Under this menu I write some string using Jquery(Home is the default value) which tells the user where he is:
<div class="Pointer"><a href="#">Home</a></div>
The following Jquery is used for detecting which category/subcategory is trigerred:
$('.tabMenu li a').click(function() {
//get current link
var currentLink = $(this);
//get link text
var linkText = currentLink.text();
//Remove all activeTab classes
$('.activeTab').removeClass('activeTab');
//Add selected class with activeTab
currentLink.parent().addClass("activeTab");
//Change pointer value according to the click
$('.Pointer a').html(linkText);
});
The Jquery function should return string which looks like Videos->Main if the user clicks subcategory 'Main' from the drop-down on 'Videos' and Games->Main if the user chooses Main from Games. This code gives only Main no matter if it was clicked from 'Games' or 'Videos' Any help will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 jQuery
closest
获取与选择器匹配的第一个祖先元素,从当前元素开始并在 DOM 树中向上推进。工作演示
You can use jQuery
closest
which get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.Working demo
试试这个:
当然,您可以在选择器
".tabMenu li #sub a"
中使用它们,但我认为这种方式更干净。Try this:
Of course you could use them both in the selector
".tabMenu li #sub a"
but I think this way is cleaner.首先,同一个 id 只能有一个实例。 (id=“子”)。将其更改为类。
尝试停止事件冒泡,换句话说,确保每次点击只执行一次脚本。
In first place, you can only have one instance of the same id. (id="sub"). Change that to a class.
Try stopping event bubbling, in other words, make sure the script is only executed once per click.