jQuery click() outputs information for wrong button multiple times

Firstly, here is my code:

$.each(obj, function(k,v) {   // k ==== key, v === value
{
    output = "";

    output = output.concat(v.info1);
    output = output.concat("<br />");

    output = output.concat(v.info2);
    output = output.concat("<br />");

    output = output.concat("<br />");

    var a = document.createElement('a');
    a.innerHTML = output;
    $("#myDiv").append(a);
    $("#myDiv").on('click', a, function(e) {
        //alert(output);
        var w = window.open("");
        w.document.write(output);
    });
});

Now, this is what I'm trying. In each iteration, I want to attach an "output" string (to "myDiv"), which on clicking, opens a new tab, and displays pertinent information (let that be the "output" string itself, for now).
Using the above code, when I click on any link, it opens as many new tabs as the number of records present, each displaying information only about the last record.
Could anybody tell what could be going wrong? Thanks!

Answers 1

  • Move $("#myDiv").on outside of the $.each like this:

    $.each(obj, function(k,v) {   // k ==== key, v === value
      output = "";
    
      output = output.concat(v.info1);
      output = output.concat("<br />");
    
      output = output.concat(v.info2);
      output = output.concat("<br />");
    
      output = output.concat("<br />");
    
      var a = document.createElement('a');
      a.innerHTML = output;
      $("#myDiv").append(a);
    });
    
    $("#myDiv").on('click', 'a', function(e) {
      var w = window.open("");
      w.document.write(this.innerHTML);
    });
    

Related Articles