【发布时间】:2019-02-20 23:22:03
【问题描述】:
我在 HTML 中创建了一些复选框,现在我想在每次选中复选框时获取其父级的类列表。
为此,我遍历检查的元素并尝试使用确实返回父级的$(this).parent(),但如果我在其末尾添加.classList,则会记录未定义。我尝试做其他事情,$(this).parent().css( "background-color", "red" ); 按计划工作。
也有可能我的函数结构不正确,但我似乎找不到错误。
有人可以指出为什么$(this).parent().classList
返回未定义?
非常感谢任何帮助。
jQuery(function($) {
function getClassList (){
$(document).ready(function(){
$('.single-checkbox').change(function() {
$('.single-checkbox').each(function() {
if( this.checked ){
console.log( $(this).parent() );
console.log( $(this).parent().classList );
$(this).parent().css( "background-color", "red" );
});
});
});
}
getClassList();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="input-wrapper post-id-145">
<input type="checkbox" class="single-checkbox">
</li>
<li class="input-wrapper post-id-116">
<input type="checkbox" class="single-checkbox">
</li>
<li class="input-wrapper post-id-176">
<input type="checkbox" class="single-checkbox">
</li>
<li class="input-wrapper post-id-151">
<input type="checkbox" class="single-checkbox">
</li>
【问题讨论】:
-
.attr('class') -
非常感谢,这行得通!你能告诉我为什么 classList 不起作用吗?
-
不客气@Zae ..但你需要知道的是:
.classList是一个纯 JavaScript$($(this).parent())[0].classList然后通过索引获取类$($(this).parent())[0].classList[1]和$(this).parent()是一个 jquery 所以你需要使用 jquery.attr('class').. 祝你有美好的一天:) .. 我想你的下一个任务是获取帖子 ID 号.. 因此我建议使用data-post-id="number"然后使用 @987654334 获取号码@ -
非常感谢,清理了一堆!! :)
标签: javascript jquery function