Get Dynamically Created Element That Was Click Javascript
Solution 1:
First of all instead of something like this
$(document).on('click', '[data-tracker]', function( event ) {
var target = event.target;
var targetName = $(target).data('tracker');
console.log(targetName);
});
You can do this
$(document).on('click', '[data-tracker]', function() {
var targetName = $(this).data('tracker');
console.log(targetName);
});
Secondly, the reason of this behavior may be because .data()
function works that way
Store arbitrary data associated with the specified element. Returns the value that was set.
So when you dynamically add an element with attribute data-tracker
there is no value set because it was not stored. So instead of using .data()
just use .attr()
.
$(document).on('click', '[data-tracker]', function() {
var targetName = $(this).attr('data-tracker');
console.log(targetName);
});
Here is a snippet
$(document).on('click', '[data-tracker]', function() {
console.log($(this).attr('data-tracker'));
});
var num = 0;
$("#addElement").on('click', function() {
$("<div>").attr('data-tracker', 'test value ' + num).html('Test value' + num).appendTo(".content");
num++;
});
[data-tracker] {
cursor: pointer;
color: #F00;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="addElement">Add element</button><divclass="content"><divdata-tracker="value1">Value 1</div><divdata-tracker="value2">Value 2</div><div>Test</div><divdata-tracker="value3">Value 3</div><divdata-tracker="value4">Value 4</div></div>
Solution 2:
Your code looks OK to me. You are probably making some mistake when added elements with JSON
, make sure you get that correct.
Here I've added a button to add elements to the page dynamically, you can verify
$(document).on('click', '[data-tracker]', function( event ) {
var target = event.target;
var targetName = $(target).data('tracker');
console.log(targetName);
});
$("#new").click(function(){
$("#d").append(`<button data-tracker="test1">test1</button>
<i data-tracker="test2">test2</i>
<img data-tracker="test3">`)
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divid="d"><buttondata-tracker="test1">test1</button><idata-tracker="test2">test2</i><imgdata-tracker="test3"></div><br/><buttonid="new">Add</button>
Solution 3:
I am assuming the data-tracker
is a class name. And here is a example of how you adding a onclick event to all element with the same class name
a = document.getElementsByClassName("data-tracker")
for (var key in a) {
if (a.hasOwnProperty(key) && Number.isInteger(parseInt(key))) {
a[key].addEventListener("click", function(){console.log('hi')});
}
}
<inputtype="button"class="data-tracker"value="button1"></input><inputtype="button"class=""value="button2"></input><inputtype="button"class="data-tracker"value="button3"></input>
Post a Comment for "Get Dynamically Created Element That Was Click Javascript"