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