是否可以从jQuery中的回调函数访问单击的元素

Possible to access clicked element from callback function in jQuery?

本文关键字:回调 函数 单击 元素 访问 jQuery 是否      更新时间:2023-09-26

我有以下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"));   
}

我想提醒从我的回调功能中点击的锚的ID,但提醒总是显示"其他"。阅读文档后:

回调没有发送任何参数,但它被设置为DOM元素设置动画。

我理解为什么,但我很好奇是否有可能做我想做的事?

Fiddle在这里可用:http://jsfiddle.net/RxcRY/

只需将ID传递给AlertSomething方法即可。

$("div#main a").click(function () {
    $("#other").fadeIn(500, AlertSomething($(this).attr("id"));
});
function AlertSomething(theID)
{
    alert(theID);   
}

这是一把正在工作的小提琴。

站点说明:

您的锚标记将用</div>而不是</a>关闭。这将导致jQuery附加到第一个锚点的点击事件,而不是后续锚点。修复标记后,jQuery将附加到div中的每个锚点。

.click((函数传入表示单击的事件对象。该对象的一部分是单击的目标,因此只需将事件处理程序传递给函数即可。

$("div#main a").click(function (e) {
    $("#other").fadeIn(500,AlertSomething(e.target));
});
function AlertSomething(obj) {
   alert($(obj).attr('id'));
}

你可以试试这个:

$("div#main a").click(function (e) {
    $("#other").fadeIn(500,AlertSomething(e));
});
function AlertSomething(e)
{
    console.log(e); // this will show you the "click" event. 
    //alert($(this).attr("id"));   
}
$("div#main a").click(function () {
   var clickedElement = $(this);
    $("#other").fadeIn(500, function() { AlertSomething(clickedElement); });
});
function AlertSomething(el)
{
     alert($(el).attr("id"));   
}

这可能有助于