我有这段代码:
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,以便我可以在另一个脚本中使用它。到目前为止它没有做任何事情。我的代码可能有什么问题?谁能帮我这个?非常感谢你。
答案 0 :(得分:5)
您拥有的代码可以正常工作,尽管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);
}
答案 1 :(得分:1)
你只需要这样做:
$(document).ready(function () {
$('#document_dropdown .notify').click(function(){
var id = this.id;
alert(id);
});
});
多数民众赞成。
答案 2 :(得分:1)
事件处理程序无法返回任何内容。您需要调用另一个脚本函数并将ID作为参数传递。
$(document).ready(function () {
$('#document_dropdown .notify').click(function(evt){
var id = this.id;
alert(id);
anotherScriptFunction(id);
evt.preventDefault();
});
});
答案 3 :(得分:1)
你可以像这样传递事件处理程序:
$(document).ready(function () {
$('#document_dropdown .notify').click(function(e){
var id = e.target.id;
alert(id);
});
});
通过这种方式,e.target
是您点击的元素。您可以通过$(e.target)
将其封装到jQuery元素中。