0

Is there a way to be able to get the literal value passed into the click() function?

<script>
var texts = ['t1', 't2', 't3', 't4', 't5'];

$(document).ready(function () {
    for (var i = 0; i < texts.length; i++) {
        var div = $("<div>");
        div.click(function () {

            div.text(texts[i]); // <---- problem here
            console.log(texts[i]); //   with texts[i]
        });

        $("#container").append(div);
    }
});
</script>

<div id="container"></div>

Intended result:

5 div elements each respectively containing the text "t1", "t2", etc.

5 div elements each, when clicked on, output the text "t1", "t2", etc. to the console.

Alternate Solution 1:

$(document).ready(function () {
    for (var i = 0; i < texts.length; i++) {
        var div = $("<div>");
        div.click({index: i}, function (e) {
            div.text(e.data.index);
            console.log(e.data.index);
        });

        $("#container").append(div);
    }
});

Alternate Solution 2:

A function can be added to set the text in the onclick event handler :

function setClick(elem, text) {
    elem.click(function () { console.log(text); });
}

So that div.click( ... ); is replaced by:

setClick(div, i);
reformed
  • 4,505
  • 11
  • 62
  • 88

2 Answers2

1

The problem is when you click the div, at that time value of i is 5, so for that you will not get any result. You should used IIFE and wrap click call in this function. Like this

$(document).ready(function () {
    for (var i = 0; i < texts.length; i++) {
        var div = $("<div>");
        div.click((function () {

            div.text(texts[i]); // <---- problem here
            console.log(texts[i]);
        })(i));

        $("#container").append(div);
    }
});
Vaibhav
  • 1,479
  • 8
  • 13
  • Accepted once the timer allows. – reformed Feb 25 '15 at 03:30
  • This actually allowed each div element to attain the particular text correctly. However, it did not solve the problem of grabbing the same text for the onclick event. I'll append the solution to my original question. – reformed Feb 25 '15 at 03:50
0

You don't need to add click handler for assigning text property before appending.

Also you should not attach the same event in loop. bind single event that should work for all of them. which can be achieved in two ways:

1) either bind the click event after appending

2) or use event delegation.

for (var i = 0; i < texts.length; i++) {
    var div = $("<div>");
    div.text(texts[i]); // <---- problem here
    console.log(texts[i]);

    $("#container").append(div);
}

$("#container div").click(function(){
   console.log($(this).text());
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125