gpt4 book ai didi

javascript - jquery $(this).attr ('href' ) 返回未定义

转载 作者:行者123 更新时间:2023-11-28 00:10:19 24 4
gpt4 key购买 nike

我有一个非常简单的代码

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)) 返回“window”,console.dir($(this)) 返回“e.fn.init[1]”

知道我做错了什么吗?代码非常简单,所以我一定错过了一些明显的东西。

我想我已经尝试了一切。

最佳答案

当您调用showForm(e)时,上下文(this)不是showForm内的 anchor 对象,而是窗口对象。

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

$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>

或使用 .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>

关于javascript - jquery $(this).attr ('href' ) 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com