简体   繁体   中英

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.

I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.

$(document).ready(function () {
            traverse(oo);
            for (i = 0; i <= groupNum; i += 1) {
                $("#a" + i).click(function () {
                    console.log("#a" + i + "clicked");
                });
            }
        });

I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?

Thanks in advance.

I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):

$("div").click(function(){
   var clickedDiv = $(this);
   var id = clickedDiv.attr("id");
});

If you don't want ALL div elements, then you could add a class to them and use a different selector:

$(".MyDivClass").click(function(){...

or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):

$("div[id^='a']").click(function(){...

If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...

$(document).on("click", ".MyDivClass", function(){...

The variable i will, as you noticed, will contains the value set on the last iteration. Change

console.log("#a" + i + "clicked");

by

console.log(this.id + " clicked");

Within the event handler, this is the target DOM element for the event.

You can do it in this way:

$('[id^="a"]').click(function () {
  console.log(this.id+" clicked");
});

You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.

    $(documnet).ready(function(){
        $('.clickclass').click(function(){
                  /* conditional code here */
        });
    });

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