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>

和以下 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/

相关文章:

javascript - IE 内部 HTML 错误

javascript - 为什么这个 JS 语法有效(额外的大括号)?

javascript - 如何在每 30 秒一次的每次 ajax 刷新上应用 Sticky Table 标题设计?

javascript - "Confirm navigation"警报框

javascript - 更改 MarionetteJS 中的 "page"

javascript - 在没有 jQuery 的情况下防止双击缩放

jquery - 你如何使用 jQuery Deferred 数组?

jQuery 单击或鼠标悬停功能未命中

jquery - 创建动态组进行验证

javascript - 将 html5 值发送到 php