Jquery 单击时不取消选择多个选择
我有一个multiple-select元素,第一个元素有一个classJquery 单击时不取消选择多个选择,jquery,select,Jquery,Select,我有一个multiple-select元素,第一个元素有一个classsel-all和其他 有sel子项 <select multiple="multiple"> <option class="sel-all">All</option> <option class="sel-child">UsernameOne</option> <option class="sel-child">UsernameTw
sel-all
和其他
有sel子项
<select multiple="multiple">
<option class="sel-all">All</option>
<option class="sel-child">UsernameOne</option>
<option class="sel-child">UsernameTwo</option>
<option class="sel-child">UsernameThree</option>
<option class="sel-child">UsernameFour</option>
</select>
全部的
用户名
用户名二
用户名三
用户名四
我想要实现的
当我点击sel all
element时,所有元素都应该被选中,并且值应该更改为Deselect all
和sel all
类将被删除,而sel del
将被添加
单击sel all
元素时,所有元素选项都将被取消选中,并且其自身也将被取消选中
现在。。这台机器不工作
您应该在此处使用委派,这样当动态添加元素时,委派的处理程序仍然有效。顺便说一句,元素选择器被过滤为委托级别,因此您切换类的逻辑得到尊重: {重构代码,并对所选属性使用.prop()而不是.attr()}
您应该在这里使用委托,以便在动态添加元素时,委托的处理程序仍然有效。顺便说一句,元素选择器被过滤为委托级别,因此您切换类的逻辑得到尊重: {重构代码,并对所选属性使用.prop()而不是.attr()}
事件处理程序附加到绑定处理程序时存在的元素,以后更改元素类不会将事件处理程序附加到该元素。您可以使用已附加到元素的单击功能,并在两种状态之间切换,而不是将事件委托给父级:
$(".sel-all").on('click', function(){
$(this).prop('selected', false)
.toggleClass("sel-del sel-all") // you can remove this, not needed
.text(function() {
return $(this).text() == 'All' ? 'Deselect All' : 'All';
}).siblings().prop('selected', $(this).text() != 'All');
});
事件处理程序附加到绑定处理程序时存在的元素,以后更改元素类不会将事件处理程序附加到该元素。您可以使用已附加到元素的单击功能,并在两种状态之间切换,而不是将事件委托给父级:
$(".sel-all").on('click', function(){
$(this).prop('selected', false)
.toggleClass("sel-del sel-all") // you can remove this, not needed
.text(function() {
return $(this).text() == 'All' ? 'Deselect All' : 'All';
}).siblings().prop('selected', $(this).text() != 'All');
});