JavaScript动态添加和删除类

这个问题在这里已经有了答案:

  • 使用JavaScript 30个答案更改元素的类

  • 由于关注的分离,考虑使用onclick属性的替代方案可能是明智的。 以下内容允许您在工作时不必考虑JavaScript而改变HTML。

    https://jsfiddle.net/gseh0wxc/2/

    var getList = (selector) => [].slice.call(document.querySelectorAll(selector));
    
    var paragraphs = getList("#divid p[id ^= 'p']");
    paragraphs.forEach((paragraph, index) => {
      paragraph.addEventListener('click', (e) => {
        for (let i = 0; i < index; i++) {
          paragraphs[i].classList.remove('active');
        }
        for (let i = index; i < paragraphs.length; i++) {
          paragraphs[i].classList.add('active');
        }
      });
    })
    

    请试试这个代码

    function test(object) {
        var pid = object.id;
        var id = parseInt(pid.split("")[1]);
        console.log(id);
        for (var i = 1; i <= id; i++) {
            var element = document.getElementById("p"+i);
            element.classList.add("active");
        }
        console.log(id+1);
        for(var i = id+1; i <= 4; i++) {
            var element = document.getElementById("p"+i);
            element.classList.remove("active");
        }
    }
    

    希望这可以帮助。


    试试这个简单的方法,而不需要提取id号和所有,并用一个简单的循环。

    function test(option) {
    //this will select all p tags id starts with "p" inside div having id "divid" and return a array
    var targetPTags = document.querySelectorAll("div#divid p[id^=p]")
    var idx, flag=false;
        //we are iterating over that array and taking each dom element in el
        for(idx=0;idx<targetPTags.length;idx++) {
            var el = targetPTags[idx];
            if(flag) {
                //do operation you want for after elements in el
            } else if(option===el) {
                flag=true; // we are making flag true when its the element that clicked and doing no operation
                //do the operation you want for the element, may be the same as below operation in else
            } else {
                //do operation you want for before element in el
            }
        }
    }
    
    链接地址: http://www.djcxy.com/p/25221.html

    上一篇: javascript dynamically adding and removing classes

    下一篇: Change Class of input element with using id