Javascript jquery$(this.attr(';href';)返回未定义的
我有一个非常简单的代码 HTML 然而,我不断得到未定义的href。log($(this))返回“window”,Console.dir($(this))返回“e.fn.init[1]” 知道我做错了什么吗?代码非常简单,所以我肯定遗漏了一些明显的东西 我想我什么都试过了 试试这个:Javascript jquery$(this.attr(';href';)返回未定义的,javascript,jquery,undefined,href,attr,Javascript,Jquery,Undefined,Href,Attr,我有一个非常简单的代码 HTML 然而,我不断得到未定义的href。log($(this))返回“window”,Console.dir($(this))返回“e.fn.init[1]” 知道我做错了什么吗?代码非常简单,所以我肯定遗漏了一些明显的东西 我想我什么都试过了 试试这个: $qqPopupCTA.on('click', showForm); // pass function name(ref) 或 调用showForm(e)时,上下文(this)不是showForm中的锚定对象,
$qqPopupCTA.on('click', showForm); // pass function name(ref)
或
调用
showForm(e)
时,上下文(this
)不是showForm
中的锚定对象,而是窗口对象
因此,您可以将函数引用作为click处理程序传递
$qqPopupCTA.on('click', showForm);
qqPopupCTA=$('.qpopupcta');
功能展示表格(e){
e、 预防默认值();
var targetPageUrl=$(this.attr('href');
警报(targetPageUrl)
//做事
}
$qqPopupCTA.on('click',showForm)代码>
根据您的方法函数setCurrent
中的此
不引用调用事件的元素。它是窗口
对象
绑定事件时只需将函数引用传递给
$qqPopupCTA.on('click', showForm);
或者,您可以使用bind()
函数showForm是全局定义的,“this”指窗口对象。
showForm(e,this)将当前元素的引用提供给函数。因此,传递“this”应该修复未定义的this(“.qqPopupCTA”)。在('click',函数showForm(){
var targetPageUrl=$(this.attr('href');
警报(targetPageUrl)
})) $qqPopupCTA.on('click',showForm)代码>它工作!我不知道第二种选择是如何起作用的。第一个没有将事件传递给e.preventDefault,但第二个运行良好。谢谢大家!@Krzysztoffłaneta第一个解决方案也应该有效——Arun的第二个解决方案有效,你的第二个也有效。谢谢大家!@Krzysztoffłaneta,即使是第一个也应该有效,这是推荐的
$qqPopupCTA.on('click', function(e){
showForm.call(this,e);
});
$qqPopupCTA.on('click', showForm);
$qqPopupCTA.on('click', showForm);
$qqPopupCTA.on('click', function (e) {
showForm.bind(this)(e);
});