Search code examples
javascripthtmlgenerated

JS Set onClick action to a Button that was create inside a loop


How to define the onClick property of the Buttons created inside this loop?.JQuery doesn't seem to work at all for that class.

    for(started somewhrere...

        var button = document.createElement('button')
        var div = document.createElement('div')
        var img = document.createElement('img')
            img.src = "../img/download.png"
        var p = document.createElement('p')
            p.appendChild(document.createTextNode("Descargar"))

        div.appendChild(img);
        div.appendChild(p);
        button.appendChild(div);

        button.onClick = "DOSOMETHINGFFS()"

        button.className = "download"

     for end somewhere...}

function DOSOMETHINGFFS(){
    alert("no")
}

BTW JQuery isn't really helping at all

$(".download").click(function() {
    alert("ok")
});

Solution

  • Make sure you're actually adding the elements to the page (e.g. container.appendChild below), and you misspelled onclick. (You had a capital C.) Otherwise, I think what you did was okay, but it's better to assign the actual function instead of a string with JavaScript code that makes a function call:

    function doSomething(url){
        console.log("download " + url);
    }
    
    var container = document.getElementById("container");
    for (var i = 0; i < 5; i++) {
        var button = document.createElement('button');
        button.innerText = "click me";
        button.className = "download";
        button.onclick = (function (url) {
            return function () {
                doSomething(url);
            };
        })("URL #" + i);
        container.appendChild(button);
    }
    
    $('.download').click(function () {
        console.log("clicked from jQuery handler");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="container"></div>

    EDIT

    Also used jQuery to add a handler. That works fine too.

    EDIT 2

    Changed the onclick example to include a different parameter for each button. There are several ways to achieve this, but I used an immediately-invoked function expression (IIFE).