Jquery - 检测单击选项禁用HTML选择

时间:2016-02-08 01:57:19

标签: javascript jquery html select



$(function(){

	$("select:option").on('click', this, function(event) {
		event.preventDefault();
		alert("a");
	});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="options" id="options">
  <option value="">Select</option>
  <option value="1">Options 1</option>
  <option value="0" disabled="disabled">Options 2</option>
  <option value="0" disabled="disabled">Options 3</option>
  <option value="0" disabled="disabled">Options 4</option>
</select>
&#13;
&#13;
&#13;

我需要查看Jquery,如果用户点击选择器的选项被禁用,如果用户点击显示警告()

示例:选择多个选项,此选项中的值为0的选项已停用,但如果用户点击其中任何一个选项已停用,则会显示警报()

<select name="options" id="options">
  <option value="">Select</option>
  <option value="1">Options 1</option>
  <option value="0" disabled="disabled">Options 2</option>
  <option value="0" disabled="disabled">Options 3</option>
  <option value="0" disabled="disabled">Options 4</option>
</select>

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

    $(function(){
        var options_sel_idx = 0;

        $("#options").on("change", this, function(event) {
            if($(this.options[this.selectedIndex]).hasClass("disabled")) {
                alert("a");
                this.selectedIndex = options_sel_idx;
            } else {
                options_sel_idx = this.selectedIndex;
            }
        });
    });
    <style type="text/css">
        .disabled {color:#808080;}
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="options" id="options">
      <option value="">Select</option>
      <option value="1">Options 1</option>
      <option value="0" class="disabled">Options 2</option>
      <option value="0" class="disabled">Options 3</option>
      <option value="0" class="disabled">Options 4</option>
    </select>