简体   繁体   中英

Javascript - onclick event is not working

So I have this piece of code:

window.onload = function () {make_buttons ('calc'); }

function make_buttons (id) {
    console.log (id);
    var input = document.createElement("INPUT");
    document.getElementById(id).appendChild(input);
    for (var i = 0;i < 10; i++){
        var btn = document.createElement ("BUTTON");
        var t = document.createTextNode (i);
        btn.appendChild(t);
        document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;    
    }
};

Now when I have created the button with the for loop, it should also have the onclick event attached to it which writes the current value of i into my input form.

Code I have written produces no errors but when the button is clicked, it simply does not do anything. Why is that?

New version:

window.onload = function () {make_buttons ('calc'); }

function make_buttons (id) {
    var input = document.createElement("input");
    input.type = 'text';
    input.id = 'inp';
    document.getElementById(id).appendChild(input);
    for (var i = 0;i < 10; i++){
        var btn = document.createElement ("button");
        btn.id = i;
        var txt = document.createTextNode (i);
        btn.appendChild(txt);
        var make_btn = document.getElementById(id).appendChild(btn);
        make_btn.onclick = button_pressed (i);
    }
};

function button_pressed (id) {
    document.getElementById("inp").value += id;
};

Method document.getElementsByTagName() returns a NodeList collection that you should iterate through. You need to go in loop through retrieved elements and assign the value attribute to each of them.

So that you can change

document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;  

to something like this:

var id = 'my-form',
    btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Click me!';
btn.onclick = function() {
    var inputs = document.getElementsByTagName('input');
    // NodeList to Array if needed:
    // var inputsArray = Array.prototype.slice.call(inputs);
    for(var i = 0, l = inputs.length; i < l; i++) {
        inputs[i].value = i;
    }
    return false;
};
document.getElementById(id).appendChild(btn);

DEMO #1


Update:

About your second question, yes it won't work in this way since at the time when your onclick event handler is called it's using the last value assigned to i variable. To avoid this you can just use closures .

For example,

HTML:

<form action="" id="my-form">
    <input type="text" id="inp" />
</form>

JavaScript:

var btn,
    input,
    form,
    createHandler;
input = document.getElementById('inp');
form = document.getElementById('my-form');
createHandler = function(i) {
    return function() {
        input.value += i;
    };
};
for(var i = 0; i < 5; i++) {
    btn = document.createElement('input');
    btn.type = 'button';
    btn.value = 'Append ' + i;
    form.appendChild(btn);
    btn.onclick = createHandler(i);
}

DEMO #2

Also you can use just immediately invoked anonymous function to create that closure in the body of your loop:

for(var i = 0; i < 5; i++) {
    // ...
    btn.onclick = (function(theNumberToAppend) {
        return function() {
            input.value += theNumberToAppend;
        };
    })(i);
}

DEMO #3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM