gpt4 book ai didi

javascript - $(this) 指的是 $(window) 而不是 .click() 方法中被点击的元素

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

<分区>

我正在尝试访问无序列表中的子元素,但我没有获得预期的值。

这是我的 HTML 代码:

<ul id="weekdayList">
<li>
<label for="sunday">S</label>
<input id="sunday" type="checkbox" name="sunday">
</li>
<li>
<label for="monday">M</label>
<input id="monday" type="checkbox" name="monday">
</li>
<li>
<label for="tuesday">T</label>
<input id="tuesday" type="checkbox" name="tuesday">
</li>
<li>
<label for="wednesday">W</label>
<input id="wednesday" type="checkbox" name="wednesday">
</li>
<li>
<label for="thursday">T</label>
<input id="thursday" type="checkbox" name="thursday">
</li>
<li>
<label for="friday">F</label>
<input id="friday" type="checkbox" name="friday">
</li>
<li>
<label for="saturday">S</label>
<input id="saturday" type="checkbox" name="saturday">
</li>
</ul>

和JS代码:

$(document).ready(() => {
// Make labels active when corresponding checkbox is checked
$('#weekdayList label').click((event) => {
event.stopPropagation();

console.log($(this));
console.log($('#weekdayList li:nth-child(2) label'));
$(this).toggleClass('active');
});
});

此处为 CodePen:https://codepen.io/mattmc318/pen/mdyEeJy

例如,当我点击“M”标签时,我希望 console.log($(this)); 的输出与console.log($('#weekdayList li:nth-child(2) label'));.

取而代之的是:

Object { 0: label, length: 1, prevObject: Object(1) }

我明白了:

Object [ Window ]

我做错了什么吗?感谢您的帮助。

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