Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery MultiSelect库使用不正确的方法处理;选择全部";?_Javascript_Jquery_Multi Select - Fatal编程技术网

Javascript jQuery MultiSelect库使用不正确的方法处理;选择全部";?

Javascript jQuery MultiSelect库使用不正确的方法处理;选择全部";?,javascript,jquery,multi-select,Javascript,Jquery,Multi Select,我正在尝试更新一个使用的大型web应用程序 我更新了最新的代码,它修复了我遇到的一个问题。但是,它引入了一个新问题:选中全选选项将取消选中所有选项,而不是选中它 我在JavaScript方面不是非常高级,但已将问题隔离到以下代码: currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () { if ($(this).attr('checked') == true)

我正在尝试更新一个使用的大型web应用程序

我更新了最新的代码,它修复了我遇到的一个问题。但是,它引入了一个新问题:选中全选选项将取消选中所有选项,而不是选中它

我在JavaScript方面不是非常高级,但已将问题隔离到以下代码:

currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
    if ($(this).attr('checked') == true)
        $(this).parent().parent().find('INPUT:checkbox').attr('checked', true).parent().addClass('checked');
    else
        $(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
});
问题是
$(this).attr('checked')
返回“checked”。因此,
$(this).attr('checked')==true
将始终为false。而且代码从来没有检测到这个选项,事实上,被选中了

好吧,我明白问题所在。但是为什么会这样写呢?解决这个问题最可靠的方法是什么?我很想知道JavaScript/jQuery专家如何解决这个问题。

而不是使用
$(this).attr('checked')==true
返回字符串try
$(this).prop('checked')==true

$.prop()
在选中元素时将返回
布尔值true
,否则将返回
布尔值false

关于
$.attr()
的一点额外信息是,它返回属性的内容。因此,如果您的html是:

<input id="elem" type="checkbox" checked="checked" />

checked
是一个属性,您应该使用
prop
方法,当一个布尔属性(如
disabled
checked
被设置到一个元素时,该值映射到元素的相关DOM属性(浏览器执行此操作),从
jQuery 1.6
开始修改属性,应使用
prop
方法,而不是
attr

所以你的代码应该是这样的

currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
    if ($(this).is(':checked'))
        $(this).parent().parent().find('INPUT:checkbox').prop('checked', true).parent().addClass('checked');
    else
        $(this).parent().parent().find('INPUT:checkbox').prop('checked', false).parent().removeClass('checked');
});

最好使用
.is(“:checked”)
检查复选框是否选中。但是使用
prop
设置复选框的
checked属性

您使用的是非常旧版本的multiselect。您现在使用的是哪个jquery版本?在花了相当长的时间查找之后,我还没有找到这种特殊风格的multiselect组件的更新版本。(我知道还有其他风格。)我使用的是jQuery 1.7.2。如果您被限制使用此文件,那么您必须将所有.attr('checked')更改为.prop('checked')。
currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
    if ($(this).is(':checked'))
        $(this).parent().parent().find('INPUT:checkbox').prop('checked', true).parent().addClass('checked');
    else
        $(this).parent().parent().find('INPUT:checkbox').prop('checked', false).parent().removeClass('checked');
});