简体   繁体   中英

jQuery click event on dynamically generated elements for calendar?

The answer to the following question ,

var counter = 0;
$("button").click(function() {
 $("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});

$("h2").on("click", "p.test", function(){
 alert($(this).text());
});

I have a dynamically generated calendar that when you click on an individual day, instead of opening a new web page, it swaps the calendar for the events of the day. The events are listed in a table and I want to be able to click on a row and and have it trigger a function which uses location.assign() . So each row looks like the following,

<tr id="message-7">

New page in calendar loads and creates,

<tr id="message-132">

Clicking does not trigger the function. In the example from the other question, it accesses the text of the element in order to make the element unique as opposed to giving the element a unique id # as in my situation.

Am I approaching the problem the wrong way? Could I add something like a "title=132" tag that I could reference?

Ideally try not to make too much meaning out of the ID. Instead use data as shown here .

So instead of

<tr id="message-7">

use

<tr id="1234567" data-message="7">

Then in code you can address the data as:

var messageVal = $("#1234567").data("message")

And if you need to add a generic click event then you might want to use a dummy css class assignment for all appropriate TR's:

 <tr id="1234567" data-message="7" class="messageRow">

so that you can write

$(".messageRow").on("click", function(event){
    event.preventDefault()
    var messageVal = $(this).data("message")

This is useful in the case where only some TR's will contain clickable content - just don't assign the class to the others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM