删除工作JQuery选项,隐藏不?

时间:2017-11-21 16:40:04

标签: javascript jquery html css dom

获得此HTML:

<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
    <option value="3">DC</option>
    <option value="5">PL</option>
    <option value="7">SA</option>
</select>

使用此javascript和amp;迭代选项jQuery的:

var departmentDDL = $(row).find('[id*="DepartmentID_"] > option');

departmentDDL.each(function () {
    if ($(this)[0].innerHTML != "SA") {
        $(this).hide();    // this does not work
        $(this).remove();  // this works
    }
});

我正在尝试隐藏选项,而不是删除它们。为什么一个工作而另一个工作?

2 个答案:

答案 0 :(得分:4)

您的(中有一个额外的if,删除它,它会起作用,但仅限Chrome浏览器中有一些小错误行为。

&#13;
&#13;
var departmentDDL = $('[id*="DepartmentID_"] > option');

departmentDDL.each(function() {
  if ($(this)[0].innerHTML != "SA") {
    $(this).hide(); // this does not work
    //$(this).remove();  // this works
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
    <option value="3" >DC</option>
    <option value="5">PL</option>
    <option value="7">SA</option>
</select>
&#13;
&#13;
&#13;

注意隐藏HTML选项在浏览器中存在多个问题,并且在某些浏览器中无法提供预期结果,有关详细信息,请查看 How to hide a <option> in a <select> menu with CSS? < / p>

答案 1 :(得分:0)

在此(删除额外的if (($(this)[0],它会正常工作

&#13;
&#13;
var departmentDDL = $('[id*="DepartmentID_"] > option');

departmentDDL.each(function () {
    if ($(this)[0].innerHTML != "SA") {
        $(this).hide();    // this does not work
        //$(this).remove();  // this works
    }else{
      $(this).parent().val($(this).val()).change();
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
    <option value="3">DC</option>
    <option value="5">PL</option>
    <option value="7">SA</option>
</select>
&#13;
&#13;
&#13;

在else部分

中选择