0

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!

1
  • take your click event out of the loop, why do you need it in there? Commented Mar 27, 2016 at 1:19

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.