我有以下 HTML:
<div id="main">
<a id="sub1">sub1</div>
<a id="sub2">sub2</div>
</div>
<div id="other" style="display:none">
some stuff
</div>
和以下 jQuery:
$("div#main a").click(function () {
$("#other").fadeIn(500,AlertSomething);
});
function AlertSomething()
{
alert($(this).attr("id"));
}
我想提醒从我的回调函数中点击的 anchor 的 ID,但提醒总是显示“其他”。在文档中阅读此内容后:
The callback is not sent any arguments, but this is set to the DOM element being animated.
我明白为什么,但我很好奇是否可以做我想做的事?
此处提供 fiddle :http://jsfiddle.net/RxcRY/
最佳答案
只需传递您的 AlertSomething
方法 ID。
$("div#main a").click(function () {
$("#other").fadeIn(500, AlertSomething($(this).attr("id"));
});
function AlertSomething(theID)
{
alert(theID);
}
这是 a working fiddle .
站点注释:
您的 anchor 标签正在用 </div>
关闭而不是 </a>
.这将导致 jQuery 附加到第一个 anchor 的单击事件,而不是后续 anchor 。修复标记后,jQuery 将附加到 div 中的每个 anchor 。
关于javascript - 可以从 jQuery 中的回调函数访问单击的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081591/