【问题标题】:Delete child nodes shorten html collection size删除子节点缩短 html 集合大小
【发布时间】:2017-04-25 17:39:53
【问题描述】:

我正在循环选择下拉选项,并希望在其值满足某些指定条件时删除一个选项。我使用了 selectObject.removechild(option)/option.remove(),但是这样做只有一个满足条件的选项首先删除,而不是其他选项,因为在每次删除操作时,列表的大小都会减小,因此不会遍历所有选项。我想要纯 JavaScript 解决方案(没有 JQuery)。我搜索了很多,只找到了 JQuery 解决方案。有没有其他办法?

var selectObject = document.getElementById("sel");
var opts = selectObject.options;
for(var i = 0; opts.length; i++){
  if(opts[i].value == val){
    opts[i].remove();
    //i also tried with: selectObject.removeChild(opts[i])
  }
}

【问题讨论】:

标签: javascript


【解决方案1】:

var empty = function() {
    s = document.getElementById('s');
    for (var i = 0; i < s.children.length; i++) {
      o = s.children[i];
      if (o.value == 2) {
        s.removeChild(o);
        i--
      }
    }
    }
<select id='s'>
 <option>1</option>
 <option>1</option>
 <option>2</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
 <option>2</option>
 <option>1</option>
 <option>1</option>
 <option>1</option>
<select>

<button onclick = 'empty()'>empty</button>

【讨论】:

    【解决方案2】:

    使用for...of loop 而不是索引,我能够让代码工作。 Here is a codepen showing it working.

    var selectObject = document.getElementById("sel");
    var opts = selectObject.options;
    for(let opt of opts){
      if(opt.value == val){
        opt.remove();
        //i also tried with: selectObject.removeChild(opts[i])
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      相关资源
      最近更新 更多