是否可以从jQuery中的回调函数访问单击的元素
Possible to access clicked element from callback function in 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"));
}
我想提醒从我的回调功能中点击的锚的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"));
}
这可能有助于
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定