我有这个代码:
HTML:
<ul class="dropdown-menu" role="menu" id="document_dropdown">
<li><a class="notify" href="toSomewhere" id="1">Item1</a></li>
<li><a class="notify" href="toSomewhere" id="2">Item1</a></li>
<li><a class="notify" href="toSomewhere" id="3">Item1</a></li>
<li><a class="notify" href="toSomewhere" id="4">Item1</a></li>
</ul>
JQuery:
$(document).ready(function () {
$('#document_dropdown .notify').click(function(){
var id = $(this).attr("id");
alert(id);
});
});
我想要实现的是查看单击了哪个 anchor 并返回该 anchor 的 ID,以便我可以在另一个脚本中使用它。到目前为止它什么也没做。我的代码可能有什么问题?谁能帮我这个?非常感谢。
最佳答案
尽管 this.id
是一种从元素中检索 native 属性的更简洁的方法,但您拥有的代码可以正常工作。如果您希望停止单击导致浏览器发出 HTTP 请求的链接,则需要将 preventDefault()
添加到您的逻辑中。
您不能从事件处理程序返回任何内容,因此如果您需要传递信息,则需要将其存储在全局变量中,或者使用该值作为参数调用另一个函数。
$('#document_dropdown .notify').click(function(e){
e.preventDefault();
var id = this.id;
alert(id);
doSomething(id);
});
function doSomething(id) {
alert('You clicked #' + id);
}
关于javascript - 如何知道在 jquery 中点击了哪个 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27353463/