我有以下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元素。
我明白为什么,但我很好奇是否可以做我想做的事?
这里提供小提琴:http://jsfiddle.net/RxcRY/
发布于 2011-08-16 16:35:02
只需将ID传递给AlertSomething方法即可。
$("div#main a").click(function () {
$("#other").fadeIn(500, AlertSomething($(this).attr("id"));
});
function AlertSomething(theID)
{
alert(theID);
}这是工作的小提琴。
站点备注:
您的锚标记正在使用</div>而不是</a>关闭。这将导致jQuery附加到第一个锚点的单击事件,而不是随后的锚点。一旦您修复了标记,jQuery将附加到div中的每个锚点。
发布于 2011-08-16 16:38:17
.click()函数传入表示单击的事件对象。此对象的一部分是单击的目标,因此只需将事件处理程序传递给您的函数。
$("div#main a").click(function (e) {
$("#other").fadeIn(500,AlertSomething(e.target));
});
function AlertSomething(obj) {
alert($(obj).attr('id'));
}发布于 2011-08-16 16:36:22
你可以试试这个:
$("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"));
}https://stackoverflow.com/questions/7081591
复制相似问题