gpt4 book ai didi

jquery - 对 jQuery 中的 'this' 关键字感到困惑

转载 作者:行者123 更新时间:2023-12-01 01:26:17 24 4
gpt4 key购买 nike

我试图找出为什么以下 3 种使用 this 关键字的方法不起作用

这是 HTML:

<ul>
<li><a id="i1" href="#">Item 1</a></li>
<li><a id="i2" href="#">Item 2</a></li>
<li><a id="i3" href="#">Item 3</a></li>
</ul>

这是 jQuery:

// Output a list of href ids and append them to the ul element
$('ul li a').each(function() {
$('<li>' + this.id + '</li>').appendTo('ul') // this works
// $(this.id).appendTo('ul') // this doesn't work
// (this.id).appendTo('ul') // this doesn't work
// $(this).attr('id').appendTo('ul') // this doesn't work
});

这里还有 jsFiddle

有人可以解释一下为什么被注释掉的 3 个代码片段都不起作用吗?

最佳答案

$(this.id).appendTo('ul') // this doesn't work

这不起作用,因为 jQuery 希望您在 $() 构造中提供元素、元素数组或字符串选择器。通过提供像 i1 这样不匹配任何内容的字符串选择器,appendTo 将不知道它应该处理哪个对象。

(this.id).appendTo('ul') // this doesn't work

这不起作用,因为 id 返回的值没有 appendTo 方法 - 请注意,您在这里没有使用 $调用 jQuery。

$(this).attr('id').appendTo('ul') // this doesn't work

这不起作用,因为 appendTo 将附加 li 对象,而不是 attr('id') 返回的字符串

问题本身似乎源于这样一个事实:您似乎对 appendTo() 有点困惑 - 基本上它附加元素,而不是字符串值。阅读the API了解更多信息。

关于jquery - 对 jQuery 中的 'this' 关键字感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13049077/

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