[英]How to disable all links inside a nested ul, except for the ones at the lowest level?
Let's say I have a list, like this: 假设我有一个清单,像这样:
<ul>
<li><a href="Sitepages/Introduction.aspx">Introduction</a>
<ul>
<li><a href="Sitepages/AboutMe.aspx">About me</a></li>
<li><a href="Sitepages/AboutTheCompany.aspx">About the company</a>
<ul>
<li><a href="Sitepages/History.aspx">History</a></li>
<li><a href="Sitepages/Locations.aspx">Locations</a>
<ul>
<li><a href="Sitepages/Belgium.aspx">Belgium</a></li>
<li><a href="Sitepages/France.aspx">France</a></li>
<li><a href="Sitepages/Germany.aspx">Germany</a></li>
<li><a href="Sitepages/Norway.aspx">Norway</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
I have a script that turns this nested ul into an accordion so that only the top levels are shown at first. 我有一个脚本可以将嵌套的ul变成手风琴,这样一开始只显示顶层。 As soon as someone clicks on a link inside a li containing another ul, it expands that ul and so on.
只要有人单击包含另一个ul的li内的链接,它就会扩展该ul,依此类推。
The thing is, while all this works fine when no links are provided, I want to disable the default behavior of every "a" tag, except for the ones at the lowest level. 问题是,尽管在没有提供链接的情况下所有这些工作正常,但我想禁用每个“ a”标签的默认行为,但最低级别的标签除外。 So the li tags at the lowest level, with a link inside them, should still be active links.
因此,处于最低级别的li标签(其中带有链接)应该仍然是活动链接。
Here's the javascript code that disables the default behavior of the top level links: 这是禁用顶级链接默认行为的JavaScript代码:
$this.find("li").each(function(){
if ($(this).find("ul").size() != 0) {
if ($(this).find("a:first")) {
$(this).find("a:first").click(function(){ return false; });
}
});
While the top level link (Introduction) will ignore the default behavior (redirecting) upon clicking, it will expand and show the "About me" and "About the company" options. 顶级链接(简介)在单击时将忽略默认行为(重定向),但它将展开并显示“关于我”和“关于公司”选项。 But when I click on "About the company", it still redirects.
但是,当我单击“关于公司”时,它仍然会重定向。
What should I edit in my code to set the default behavior of every "a" tag to false, except for the last ones (in my example: the country names)? 除了最后一个(在我的示例中:国家/地区名称)之外,我应如何在代码中进行编辑以将每个“ a”标签的默认行为设置为false?
Thanks for your help! 谢谢你的帮助!
You can setup two handlers. 您可以设置两个处理程序。 One to disable all links within an unordered list and another to handle clicks on the last unordered list:
一种用于禁用无序列表中的所有链接,另一种用于处理对最后一个无序列表的单击:
// Disable all links within an ul
$('ul').on("click", "a", function(e){
e.preventDefault();
});
// second handler to bind to the last ul
$('ul:last').on("click", "a", function(e){
window.location.href = $(e.target).attr('href');
});
Fiddle: http://jsfiddle.net/puleos/CjB99/ 小提琴: http : //jsfiddle.net/puleos/CjB99/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.