我最近遇到了JavaScript代码问题。单击3次后,脚本会将其<ins data-ad-slot="4092520690">参数更改为<ins data-ad-slot-"9020596432">。但是有一个轻微的控制台错误。
它说“ ins1.addEventListener不是函数”。

错误:

javascript代码:

$(document).ready(function(){
        if(sessionStorage.getItem('ins')){
            const ins1 = document.getElementsByTagName('4092520690');
            var newIns = sessionStorage.getItem('ins');
            var newParam = sessionStorage.getItem('param')
            ins1.param = newParam;
            ins1.innerText = newIns;
        }
    });

    function replaceAfter3Clicks(elem, newElem) {
        let count = 0;
        ins1.addEventListener('click', () => {
            count ++;
            if (count === 3) {
                sessionStorage.clear(); // Clear all sessionStorage
                sessionStorage.setItem('ins', "ins 2"); // First param is the name and the second is the value
                sessionStorage.setItem('data-ad-slot', "4092520690");// First param is the name and the second is the value
                elem.parentNode.replaceChild(newElem, elem);
            }
         });
    }

    const ins1 = document.getElementsByTagName('4092520690');

    // pre-made second div for future replacement
    const ins2 = document.createElement('ins');
    ins2.param = '9020596432';
    ins2.innerText = 'ins 2';
    replaceAfter3Clicks(ins1, ins2);


有人可以启发我线的问题是什么

ins1.addEventListener('click', () => {

replaceAfter3Clicks(ins1, ins2);是。

最佳答案

您的问题是ins1不是元素,而是元素的类似数组的对象。而且数组(也不是类似数组的对象)不能添加事件侦听器。

您需要做的是浏览ins1并将事件侦听器添加到其中的每个元素。就像是:

function replaceAfter3Clicks(elem, newElem) {
    let count = 0;
    let callback = function() {
        count ++;

        if (count === 3) {
            sessionStorage.clear(); // Clear all sessionStorage
            sessionStorage.setItem('ins', "ins 2"); // First param is the name and the second is the value
            sessionStorage.setItem('data-ad-slot', "4092520690");// First param is the name and the second is the value
            elem.parentNode.replaceChild(newElem, elem);
        }
    };

    Array.from(ins1).forEach(element => {
        element.addEventListener('click', callback);
    }
});

09-18 15:40