繁体   English   中英

jQuery $(this).attr('href')返回未定义

[英]jquery $(this).attr('href') returns undefined

我有一个非常简单的代码

HTML

<a class="qqPopupCTA" href="http://example.com">Button</a>

JS

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e){

    e.preventDefault();

    var targetPageUrl = $(this).attr('href');

    // do stuff
}

$qqPopupCTA.on('click', function(e){showForm(e);});

但是我一直得到不确定的href。 Console.log($(this))返回“窗口”,console.dir($(this))返回“ e.fn.init [1]”

知道我在做什么错吗? 该代码非常简单,因此我必须缺少明显的东西。

我想我已经尝试了一切。

当您调用showForm(e) ,context( this )不是showForm内的锚对象, showForm窗口对象。

因此,您可以将函数引用作为点击处理程序传递

$qqPopupCTA.on('click', showForm);

 $qqPopupCTA = $('.qqPopupCTA'); function showForm(e) { e.preventDefault(); var targetPageUrl = $(this).attr('href'); alert(targetPageUrl) // do stuff } $qqPopupCTA.on('click', showForm); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a class="qqPopupCTA" href="http://example.com">Button</a> 

或使用showForm .call()将自定义上下文传递给showForm函数

$qqPopupCTA.on('click', function (e) {
    showForm.call(this, e);
});

 $qqPopupCTA = $('.qqPopupCTA'); function showForm(e) { e.preventDefault(); var targetPageUrl = $(this).attr('href'); alert(targetPageUrl) // do stuff } $qqPopupCTA.on('click', function(e) { showForm.call(this, e) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a class="qqPopupCTA" href="http://example.com">Button</a> 

尝试这个:

$qqPopupCTA.on('click', showForm); // pass function name(ref) 

要么

$qqPopupCTA.on('click', function(e){
      showForm.call(this,e);
});

按照您的方法, this函数在setCurrent中并不引用调用事件的元素。 它是window对象

只需将函数引用传递给绑定事件

$qqPopupCTA.on('click', showForm);

或者,您可以使用bind()

$qqPopupCTA.on('click', function (e) {
    showForm.bind(this)(e);
});

函数showForm是全局定义的,“ this”是指window对象。 showForm(e,this)将给函数提供当前元素的引用。因此传递'this'应该可以解决您未定义的this

$('。qqPopupCTA')。on('click',function showForm(){var targetPageUrl = $(this).attr('href'); alert(targetPageUrl)

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM