我有以下代码:
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);
});
});
我要实现的是查看单击了哪个锚点并返回该锚点的ID,以便可以在另一个脚本中使用它。到目前为止,它什么也没做。我的代码可能出什么问题了?谁能帮我这个?非常感谢你。
尽管这this.id
是从元素中检索本机属性的一种更为简洁的方法,但是您拥有的代码可以正常工作。如果希望停止单击链接以使浏览器发出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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句