[英]How to disable the drop down menu if no element is there in it
我正在開發一個項目,我想在沒有添加任何元素的情況下禁用下拉菜單(在添加一些選項后它將變為活動狀態)就像在這個例子中,下拉列表是空的但它仍然有效(我可以點擊它)。 我想禁用該屬性。
小提琴的例子是: http : //jsfiddle.net/7aqZm/
function myFunction()
{
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
使用jQuery,你可以這樣做:
if ($("option#mySelect").length === 0) {
$("#mySelect").css('display', 'none');
// this hides the select if it's empty
// if you want to disable, comment the previous line
// and uncomment the next one
// $("#mySelect").prop('disabled', 'disabled');
}
您還可以在$(#mySelect)中查找子項。 您可以使用相反的功能(從禁用選擇開始並通過jquery啟用它):
$("#mySelect").css('display', 'block') // or 'inline' or...
$("#mySelect").prop('disabled', false); // for enabling
記得在必要時打電話。
您可以從設置元素的disabled屬性開始。 添加新元素后,可以刪除已禁用的屬性。
所以:
<select id="mySelect" size="8" disabled="disabled"></select>
和javascript:
function myFunction()
{
var x = document.getElementById("mySelect");
x.disabled = false;
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
只是為了獎勵,您還可以使用:empty偽選擇器設置select元素的樣式(注意您必須刪除open和close標記之間的所有內容,包括空格)
CSS:
#mySelect:empty {
background-color: red;
}
檢查這個http://jsfiddle.net/286qL/
將disable值設置為true,並在添加內容時將其刪除。
document.getElementById("mySelect").setAttribute('disabled', true);
function myFunction()
{ document.getElementById("mySelect").removeAttribute('disabled');
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = "Kiwi";
x.add(option);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.