有了这个
示例 1
$("#my_div").on("click", function () {
alert( $(this).attr("id") )
});
我们得到了正确的结果,但如果我使用这个:
示例2
function thisId () {
alert( $(this).attr("id") )
}
$("#my_div").on("click", function () {
thisId();
});
现在结果未定义。请告诉我,当使用 this
的选择器和函数被编写为不同的表达式时(如示例 2 中所示),我应该如何使用 this
?
最佳答案
为了让 jQuery 将元素引用传递给函数,您必须提供函数作为引用。试试这个:
$("#my_div").on("click", thisId);
@bot 更新
function thisId (event) {
alert( $(this).attr("id") )
alert(event.type);
}
$("#my_div").on("click", thisId);
关于javascript - 当函数和选择器不在一起时使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13294350/