问题
Let say I have 5 element from PHP query (so it is dynamic) Illustrated below:
element 1 class=element id=id_1
element 2 class=element id=id_2
element 3 class=element id=id_3
element 4 class=element id=id_4
element 5 class=element id=id_5
We ussulay use jquery event by knowing their class or id, but in this case, we don't know exactly their id.
$("#id_3").click(function()
{
//in this case we have known we want to add event when we click id_3
});
How to deal with dynamic element from PHP query?
For example, how can we know that we click on element 3 with id_3?
What must we fill in $(????).click();?
When I use class, how can I know which id I reference from the class clicked?
回答1:
In your example the elements all have the same class, so you can setup your event handler based on that:
$(".element").click(function() {
// "this" refers to the clicked element
// this.id will be the id of the clicked element
});
Or if these elements are dynamic in the sense of being loaded via Ajax at some point after the initial page load use a delegated event handler:
$("somecontainerelement").on("click", ".element", function() {
// do something with this.id
});
Where "somecontainerelement" would ideally be the element that the dynamic elements are added to, but could just be document.
回答2:
This was the only way I could get it to work. For example, if you wanted to get the attribute ID or the value of the element that has been clicked...
$("containerElem").on("click", "someElemID", function(evt) {
var getElemID = $(evt.target).attr("id");
var getVal = $(evt.target).val();
});
回答3:
If they all have the same class, then you can use a class selector. Then use this to find whatever property you are after.
$('.element').click(
$(this).prop('id');
);
回答4:
If you want to add a click only then why not add that to the generated html on server side?
回答5:
You can use attribute starsWith selector & on to bind events on dynamically created elements.
$('body').on('click', '[id^=id]', function(e){
});
回答6:
This is veryusefull when we work on unknown elements with id or class
$( document ).ready(function() {
// user this if element is div
$('div[id^="id_"]').on('click', function() {
alert($(this).attr('id'));
});
// user this if element is input
$('input[id^="id_"]').on('click', function() {
alert(this.id);
});
});
来源:https://stackoverflow.com/questions/10576876/jquery-get-id-or-class-from-dynamic-element