问题描述
我用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>
1楼
imvain2
0
2019-02-20 23:27:49
您的代码有太多需要清理的地方。 以下是有效的清理版本。 您的IF缺少结尾}和..
这些基本上执行相同的jQuery(function($){和$(document).ready(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().attr('class')); $(this).parent().css( "background-color", "red" ); } }); }); });
<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>
2楼
sathish kumar
0
2019-02-20 23:34:31
尝试这个。 您无需选中ischecked或遍历所有复选框。
jQuery(function($) { $(".single-checkbox").change(function(){ let classNames = $(this).parent().attr('class'); //list of parrent classnames in array console.log(classNames.split(" ")); }) });
<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>