1

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")
});
Wesos de Queso
  • 1,526
  • 1
  • 21
  • 23

3 Answers3

3

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).

user94559
  • 59,196
  • 6
  • 103
  • 103
1

This will handle the click events of any element added dynamically to the dom.

$('body').on("click",".download" , function() {
    alert("ok");
});
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
0
$(".download").click(function() {
    alert("ok")
});

The above code will work in case the button has been already in the DOM , since you are creating it dynamically so you need to bind the click on the parent element as

$(document).on('click','.download',function(){
  alert('ok');
});
Rahul
  • 2,374
  • 2
  • 9
  • 17