簡體   English   中英

將禁用的選定屬性放入變量中選擇框的匹配值

[英]put disabled selected attribute into a match value of the select box from a variable

我有這個選擇框(請參閱下文)

<select name="test">
    <option value="option1" disabled selected">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
</select>

和這個jQuery代碼(請參閱下文)

var valueofselectbox = "option3";
//loop each option from this select box
$('select option').each(function(){
    //remove all the disabled and selected attribute from all the option within this select box.
    $(this).attr("disabled", "");
    $(this).attr("selected", "");
    //if the variable valueofselectbox is equal to this value then add disabled and selected attribute to this option
    if(valueofselectbox == $(this).val(){
        $(this).attr("disabled selected");
    }
});

現在,從上面可以看到,首先我有一個變量名valueofselectbox,然后接下來,我遍歷該選擇框內的所有選項,然后從該選擇框內的每個選項中刪除Disabled和selected屬性,然后添加Disabled和selected屬性,如果它的值(選項值)等於該變量,但似乎不起作用,則從控制台出現此錯誤“ Uncaught ReferenceError:未定義”。

你應該用

$(this).removeAttr("disabled");
$(this).removeAttr("selected");

來自jQuery文檔: http : //api.jquery.com/removeattr/

設置一個屬性時,一次要使用1個屬性名稱,因此您可以使用:

$(this).attr("disabled", "");
$(this).attr("selected", true);

https://api.jquery.com/attr/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM