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

Javascript 是否可以从jQuery中的回调函数访问单击的元素?,javascript,jquery,Javascript,Jquery,我有以下HTML: <div id="main"> <a id="sub1">sub1</div> <a id="sub2">sub2</div> </div> <div id="other" style="display:none"> some stuff </div> 我想提醒从我的回调函数中单击的锚的ID,但该提醒始终显示“其他”。阅读文档中的内容后: 回调不会发送任

我有以下HTML:

<div id="main">
    <a id="sub1">sub1</div>
    <a id="sub2">sub2</div>
</div>
<div id="other" style="display:none">
 some stuff    
</div>
我想提醒从我的回调函数中单击的锚的ID,但该提醒始终显示“其他”。阅读文档中的内容后:

回调不会发送任何参数,但会设置为DOM 正在设置动画的元素

我明白为什么,但我很好奇是否有可能做我想做的事


这里有小提琴:

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

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

function AlertSomething(theID)
{
    alert(theID);   
}
给你

网站说明:

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

您可以尝试以下操作:

$("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"));   
}
这可能会很有帮助,.click()函数会传入表示单击的事件对象。这个对象的一部分是单击的目标,所以只需将事件处理程序传递给函数即可

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

function AlertSomething(obj) {
   alert($(obj).attr('id'));
}

您确定可以传递参数吗?我以为他们说你不能:
回调没有发送任何参数…
我太习惯mootools了,在mootools中,大多数东西都被包装在moo对象中。
$("div#main a").click(function () {
   var clickedElement = $(this);
    $("#other").fadeIn(500, function() { AlertSomething(clickedElement); });
});

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

function AlertSomething(obj) {
   alert($(obj).attr('id'));
}