javascript 如何使用jquery从选项中删除“selected”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13858077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:59:18  来源:igfitidea点击:

How to delete "selected" attribute from option using jquery

javascriptjqueryjquery-uijsp

提问by Uzair

I want to remove the "selected" attribute from an option element when I uncheck this. I dont want to make value false or anything... I just want to delete this property. My code is like

当我取消选中此项时,我想从选项元素中删除“selected”属性。我不想让 value false 或任何东西......我只想删除这个属性。我的代码就像

$(function() {
  $("#deployselect").multiselect({
    click: function( event, ui ) {
      if(ui.checked==false){
        $("#deployselect option[value='"+ui.value+"']").removeAttr("selected");
      }
    }
  });
});

My generated HTML is like this

我生成的 HTML 是这样的

<option value="68" selected>A1</option>
<option value="49" selected>A2</option>
<option value="69" selected>A3</option>

so even i make "attr" or "prop" false it is not working. :(

所以即使我将“attr”或“prop”设为假,它也不起作用。:(

回答by T.J. Crowder

If you want to de-select it, change this line:

如果要取消选择它,请更改此行:

$("#deployselect option[value='"+ui.value+"']").removeAttr("selected");

to

$("#deployselect option[value='"+ui.value+"']").prop("selected", false);

Live Example| Source

现场示例| 来源

(Assuming jQuery 1.6 or later; for earlier versions, change propto attr.)

(假设 jQuery 1.6 或更高版本;对于早期版本,更改propattr.)

Once the HTML has been parsed into the DOM, the optionelementhas a property called selectedwhich gets its initial value from the selectedattribute in the HTML (defaulting to false). So once you're dealing with DOM elements, you're dealing with a boolean property, not an attribute anymore.

一旦 HTML 被解析为 DOM,option元素就会一个被调用selectedselected属性,该属性从 HTML 中的属性(默认为false)中获取其初始值。因此,一旦您处理 DOM 元素,您就处理的是一个布尔属性,而不是属性。

回答by StudioX

A simple option is to set selector value to empty so all checked list will uncheck

一个简单的选项是将选择器值设置为空,以便所有选中的列表都将取消选中

$("#deployselect").val([]);