How can I disable an

后端 未结 6 1361
囚心锁ツ
囚心锁ツ 2020-11-27 16:13

I have a ... var op = document.getElementById("foo").getElementsByTagName("option"); for (var i = 0; i < op.length; i++) { // lowercase comparison for case-insensitivity (op[i].value.toLowerCase() == "stackoverflow") ? op[i].disabled = true : op[i].disabled = false ; }

Without enabling non-targeted elements:

// Get all options within 
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");

​ Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

提交回复
热议问题