关于table里面的checkbox选择无效的问题

版权声明:本文不管是不是原创,欢迎转载。 https://blog.csdn.net/alanfancy/article/details/49997271

废话不多说, 直接看代码

XX.html

 <table class="table tableEvent">
                        <thead>
                            <tr>
                                <th> </th>
                                <th>ID</th>
                                <th>题型</th>
                                <th>试题文本</th>
                                <th>保存日期</th>
                                <th>教材版本</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="checkbox"></td>
                                <td>1000100</td>
                                <td>选择题</td>
                                <td>植物光合作用</td>
                                <td>2016/12/12 20:00:26</td>
                                <td>教科版</td>
                            </tr>
                            <tr>
                                <td><input type="checkbox"></td>
                                <td>1000100</td>
                                <td>选择题</td>
                                <td>植物光合作用</td>
                                <td>2016/12/12 20:00:26</td>
                                <td>教科版</td>
                            </tr>
</tbody></table>
<script src="jquery-1.11.1.min.js"></script>

XX.js

$(function(){
		$('.tableEvent tbody tr').click(function(){
			var input=$(this).find('td:first-child').children('input[type=checkbox]');
			if($(input).is(":checked")){
<span style="white-space:pre">				</span>$(input).attr('checked',false);
<span style="white-space:pre">			</span>}else{
<span style="white-space:pre">				</span>$(input).attr('checked',true);
<span style="white-space:pre">			</span>}
		})
	})

这样就会有一个问题, checkbox第一次选中,再取消,是正常的,再次选择的时候,就会出现选不上的情况, 查看实时代码发现,checkbox的checked属性其实是加上去了的,但是勾勾没有出选,也就是没有被选中,至于为什么出现这种情况,网上的说法都集中在attr的身上, 把attr换成prop, 但是我也试了,根本没卵用, 百思不得其姐...

其实: checked=''  也是表示true的 <input type='checkbox' checked=" " > 也是表示已选中的

后来查AIP, 发现prop有这样一个方法

$("input[type='checkbox']").prop("checked", function( i, val ) {
  return !val;
});

直接放到click事件里,测试一下OK了

$('.tableEvent tbody tr').click(function(){
			var input=$(this).find('td:first-child').children('input[type=checkbox]');
			$(input).prop("checked", function( i, val ) {
			  return !val;
			});
})



猜你喜欢

转载自blog.csdn.net/alanfancy/article/details/49997271