V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
TestSmirk

javascript for 循环删除 html 元素和 interval 删除有什么不同?

  •  
  •   TestSmirk · Oct 17, 2017 · 3819 views
    This topic created in 3113 days ago, the information mentioned may be changed or developed.

    interval 删除 这个是成功删除的.

    function removeIds(id) {
    
        var  num = document.querySelectorAll(id).length;
        var j = setInterval(function () {
            if(num>0){
                num--;
                document.querySelector(id).remove();
            }else {
               clearInterval(j);
            }
        })
    }
    

    for 循环删除(这个是失败的)

    var classNames = document.getElementsByClassName("classname");
        for(var i=0;i<classNames.length; i++){
            classNames[i].remove();
        }
    

    请问有什么不同吗.为什么 for 删不掉(删掉的是第 0 个).而 interval 却能删掉.

    Supplement 1  ·  Oct 17, 2017
    感谢大家的回复,不了解 js 这种东西.今天学到很多东西.
    Supplement 2  ·  Oct 18, 2017
    基础不好.>_<
    12 replies    2017-10-18 13:27:26 +08:00
    chairuosen
        1
    chairuosen  
       Oct 17, 2017   ❤️ 1
    for 循环最后打印 classNames.length 你就知道了
    flowfire
        2
    flowfire  
       Oct 17, 2017   ❤️ 1
    var length = classNames.length
    for(var i=0;i<length ; i++){
    classNames[0].remove();
    }
    morethansean
        3
    morethansean  
       Oct 17, 2017   ❤️ 1
    楼主操作骚得不知道怎么吐槽 23333 ……你把 setInterval 改成 for 一样能删啊……
    做实验要对比,除了对比参数外还有别的变量是怎么回事……一个是 NodeList 一个 HTMLCollection ……
    flowfire
        4
    flowfire  
       Oct 17, 2017
    @morethansean #3 23333 一波骚操作。这个方法可以用来删除奇数节点
    daisyxdx
        5
    daisyxdx  
       Oct 17, 2017   ❤️ 1
    傻孩子,classNames 的 length 是会变的啊
    lianyue
        6
    lianyue  
       Oct 17, 2017 via iPhone
    哈哈哈哈
    enginex
        7
    enginex  
       Oct 17, 2017
    querySelector 返回 no-live collection
    shangfabao
        8
    shangfabao  
       Oct 17, 2017
    你倒序删除试试?
    renminghao
        9
    renminghao  
       Oct 17, 2017
    classNames[i--].remove();
    SourceMan
        10
    SourceMan  
       Oct 17, 2017
    说一下:这不能归结于不了解 js
    chenyu8674
        11
    chenyu8674  
       Oct 18, 2017
    LZ 是基本功问题,JS 表示这锅我不背
    wuzhizhemu569
        12
    wuzhizhemu569  
       Oct 18, 2017 via Android
    这个与编程语言无关
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   868 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 22:00 · PVG 06:00 · LAX 15:00 · JFK 18:00
    ♥ Do have faith in what you're doing.