在动态更改函数的 class 后,单击按钮会重复触发相同的函数吗?

The same function gets fired repetedly on button click after dynamic changing the class of the function?

我正在尝试在“js”中创建一个函数,该函数可以 change/replaces 给定元素的属性值。但是我遇到了在动态更改按钮 class 后触发相同功能的问题,这次应该在点击时触发另一个功能。

我的代码:

<p>Hello world</p>
<button class="top2">Change Size</button>
<script>
    //Note:- function "data_exists" check if a data exists in the array or string;
   // And add_attr adds an attribute or values to a existing attr
    
    function eventlisten(elem, eventType, func) {
        if(document.contains(elem)){
           elem.addEventListener(eventType, func);
        }
    }

    // Fired when the button.top2 is clicked [1st function]
    eventlisten(document.querySelector('button.top2'), 'click', function(){
        let p = document.querySelector('p'); // gets the p element
        add_attrs(p, {'class': 'size'}, true); // adds the attr
        changeAttrValue(document.querySelector('button.top2'), 'class', 'top2', 'undo_size'); // Changes the button class to 'undo_size'
    });

    // Fired when the button.undo_size is clicked [2nd function]
    eventlisten(document.querySelector('button.undo_size'), 'click', function(){
        let p = document.querySelector('p.size');// gets the p element
        add_attrs(p, {'class': 'top3'}, true);// adds the attr
        changeAttrValue(elem=document.querySelector('button.undo_size'), attr='class', oldAttr='undo_size', newAttr='top2'); // Changes the button class to 'top2'
    });
    
</script>

点击 button.top2 后元素看起来:

<p class="size">Hello world</p>
<button class="undo_size">Change Size</button>

第一个函数工作正常,但这次当按下按钮时,第一个函数会再次触发,而不是第二个函数

我应该怎么做才能防止触发第一个函数而第二个函数应该被触发。

提前感谢所有阅读我的问题的人。

document.querySelector('button.top2')

returns 对 button 的引用,恰好在那一刻有 class top2addEventListener 然后将事件侦听器附加到该特定元素。它不是 know/care 你最初碰巧用 class.

引用那个元素
document.querySelector('button.undo_size')

returns(此时在您的脚本中调用时)总是 null。那个时候classundo_size没有button,以后有没有也无所谓

我想这就是您创建(基本上毫无意义的)函数 eventlisten 的方式,因为当您尝试在 null 上调用 addEventListener 时出现错误。 if (document.contains(elem)) 在你的情况下只是检查 if (elem !== null) 的一种不同方式,因为 document.contains(null) 总是 returns false.

可能有一种切换事件处理程序的方法,但它可能更容易,只需要一个事件处理程序并检查设置了哪个 class。像这样:

eventlisten(document.querySelector('button.top2'), 'click', function(){
        let p = document.querySelector('p'); // gets the p element
 
        // `this` in the event handler refers to the button that was clicked on
        if (this.classList.contains('undo_size')) {
            add_attrs(p, {'class': 'top3'}, true);// adds the attr
            changeAttrValue(this, 'class', 'undo_size', 'top2'); // Changes the button class to 'top2'
        } else {
            add_attrs(p, {'class': 'size'}, true); // adds the attr
            changeAttrValue(this, 'class', 'top2', 'undo_size'); // Changes the button class to 'undo_size'
        }
    });

顺便说一句,最后一行的赋值(elem=attr= 等)意义不大。 JavaScript 没有命名参数,如果这是你想要的)。