javascript 如何检查我的 <select> 元素是否包含 multiple 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11316504/
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 12:44:26  来源:igfitidea点击:

how can I check to see if my <select> element contains the multiple attribute

javascriptjquery

提问by arrowill12

hi I have tried many options to check if the multiple attribute is set in my select box but none have worked. I am trying to determine if the current select box that I am getting values from is a multiple select so far this is what I have tried:

嗨,我尝试了很多选项来检查我的选择框中是否设置了多个属性,但没有一个有效。我正在尝试确定我从中获取值的当前选择框是否是一个多重选择,这是我尝试过的:

if($(":select[multiple]").length){
           alert("worked");
}

also

if($("select").attr("multiple"){
           alert("worked");
}

also

if($("select").attr("multiple") != 'undefined'{
           alert("worked");
}

html:

html:

<select multiple="multiple" style="height:50px" class="classname" name="multi_values[]"> 
 <option value="blah">blah</option> 
 <option value="blah">blah</option> 
 <option value="blah">blah</option>              
</select>

回答by mgraph

remove :at the beginning of :

:在开头删除:

if($("select[multiple]").length){
    alert("worked");
}

Demo: http://jsfiddle.net/D5JX5/

演示http: //jsfiddle.net/D5JX5/

回答by Stano

Also simple javascript check:

也简单的javascript检查:

var c = document.getElementsByTagName('select'); //collection
for (var i=0, l = c.length; i<l; i++) {
    alert(typeof c[i].attributes['multiple'] == 'undefined' ? 'single':'multiple');
}

And jQuery equivalent:

和 jQuery 等价的:

$('select').each(function(){
  alert( typeof this.attributes['multiple'] == 'undefined' ? 'single':'multiple' );
});

回答by Chandu

All the options except ":select[multiple]"(shd be "select[multiple]") you tried should work.

除了":select[multiple]"(shd be "select[multiple]") 您尝试过的所有选项都应该有效。

JSFiddle: http://jsfiddle.net/VAXF6/2/

JSFiddle:http: //jsfiddle.net/VAXF6/2/

However you are missing a closing paran for your if statement.

但是,您缺少 if 语句的结束句。

Change your code to:

将您的代码更改为:

if($("select[multiple]").length){
           alert("worked");
}

or

或者

if($("select").attr("multiple")){
           alert("worked");
}

or

或者

if($("select").attr("multiple") != 'undefined'){
           alert("worked");
}

Another alternative:

另一种选择:

if($("select").is("[multiple]")){
           alert("worked");
}

回答by Grinn

It seems you need to only alert if multiple was set with a value, not just if it exists as an attribute:

似乎您只需要在 multiple 设置了一个值时才需要发出警报,而不仅仅是它是否作为属性存在:

if($("select[multiple='multiple']").length){
    alert("worked"); 
}