gpt4 book ai didi

javascript - $(this) 抛出 "undefined"但这按预期工作

转载 作者:行者123 更新时间:2023-11-30 16:09:04 25 4
gpt4 key购买 nike

请考虑两段代码。

1) 按预期工作:

  $(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = this.textContent;
choice.textContent = text;
});
});

2) 在这种情况下,$(this) 抛出“undefined”。

$(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = $(this).textContent;
choice.textContent = text;
});
});

很长一段时间以来,我一直在使用 $(this) 作为对所选元素的引用。但是今天失败了。怎么了?我是否应该忘记 $(this) 而不再在几行简单代码中面对这种情况?

Codepen

最佳答案

.textContenta DOM property ,而不是 jQuery 属性或方法。这就是为什么作为 jQuery 元素的 $(this) 没有它。

您可以使用 $(this)[0] 从 jQuery 元素中获取实际的 DOM 属性,如下所示:

var text = $(this)[0].textContent;

但是 $(this)[0] 等同于 this 所以在那个特定的例子中这样做是没有意义的。它在其他情况下可能有意义 - 例如,如果您将 jQuery 元素作为函数参数:

function set_text(jqElem,txt) { jqElem[0].textContent = txt; }

您还可以使用 the jQuery method .text() 获取或设置元素的文本内容,像这样:

var text = $(this).text();

关于javascript - $(this) 抛出 "undefined"但这按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549247/

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