Catching click events on <a> elements that are programmatically added to the DOM

I have an AJAX callback that returns a list of results that are written as links within a specific one div. The code looks something like this:

$.each(data, function (idx, item) {
    var a = document.createElement("a");
    a.innerText = item.name;
    a.href = "#";
    // TODO set handler for click event
    d.appendChild(a);
    d.innerHTML += "<br/>";
});

This works great and links appear. However, I want to perform some actions when clicking links. itemhas some other properties that I will need in the click handler, so I would like to close them. Here's the definition of a handler:

    // defined in loop as a closure
    var clickHandler = function() {
        $('#siteId').value = item.siteId; // closed over this property
        $('#siteName').value = item.name; // and this one
        return false;
    };

I tried several methods of providing this click event handler. Firstly:

    a.onclick = clickHandler;

Secondly:

    a.addEventListener("click", clickHandler, true);  

I also tried the events mouseup, mousedownbut they do not work either.

, , , # ( URL-).

? , jQuery, ?

+3
4
d.innerHTML += "<br/>";

. innerHTML+= . HTML, DOM. , HTML, , JS . , , <a>, .

HTML ; . HTML ( HTML, ), HTML .

, DOM:

d.appendChild(document.createElement('br'))

a.innerText = item.name;

IE, . IE, textContent , document.createTextNode() a.

, , jQuery, text() click() , .

+2

- jQuery:

$.each(data, function (idx, item) {
  $("<a />", { text: item.name, href: '#', click: clickHandler })
     .appendTo(d).after('<br />');
});

$(html, props) , href . .appendTo(), d, <br />, , .after().

+2

jQuery, ?

jQuery DOM :

$(a).click(clickHandler);

, , . , val, value:

var clickHandler = function() {
    $('#siteId').val(item.siteId); // closed over this property
    $('#siteName').val(item.name); // and this one
    return false;
};
+1

jQuery.live, , . . jQuery:

http://api.jquery.com/live/

, DOM .

0

Source: https://habr.com/ru/post/1760851/


All Articles