JavaScript interview question: Generate ten buttons, and pop up 1-10 every time you click it

1. Use custom functions

for (i = 1; i <= 10; i++) {
    
    
    (function (i) {
    
    
        var btn = document.createElement("button");
        btn.innerText = i;
        btn.onclick = function () {
    
    
            alert(i);
        }
        document.body.appendChild(btn);
    })(i);
}

// This is because the self-executing function forms an independent function scope
// If we remove the self-executing function, the pop-up prompt will be 11 every time we execute a click event
// This is because when the code is executed, the For loop It is executed instantly when the page is loaded,
// and the click event is executed when we click to start. That is to say, when the click event is executed, i has become 11

2. We can also use the following method to pop up innerText or innerHTML

for (i = 1; i <= 10; i++) {
    
    
    var btn = document.createElement("button");
    btn.innerText = i;
    btn.onclick = function () {
    
    
        alert(this.innerText);
    }
    document.body.appendChild(btn);
}

3. Another option is to add a custom attribute to each button to record their index.

for (var i = 1; i <= 10; i++) {
    
    
    var btn = document.createElement("button");
    btn.innerText = i;
    // 给每个生成的按钮添加一个自定义属性,并赋值i
    btn.setAttribute('index',i);
    btn.onclick = function () {
    
    
        alert(this.getAttribute('index'));
    }
    document.body.appendChild(btn);
}

4. We can also use ES6 syntax and use let directly.

// 这里是因为let声明的变量会自动生成一个块级作用域
for (let i = 1; i <= 10; i++) {
    
    
    var btn = document.createElement("button");
    btn.innerText = i;
    btn.onclick = function () {
    
    
        alert(i);
    }
    document.body.appendChild(btn);
}

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/118096727