简体   繁体   中英

Click event added to appended html; element not working as anticipated

OK I am sure I am doing something simple fundamentally wrong but am unable to resolve this issue on my own. I have tried googling and searching this forum and reading through the relevant parts of the jquery documentation.

If you need any further information please let me know. Many thanks in advance.

What I am trying to do:

I have a table showing details of various tests at the bottom of which I have a button to ad a new test. As each test comprises several rows of the table I have a template in a hidden div which I have cloned and appended to the live table. I am the using jquery to add appropriate classes and ids based on a variable integer for the sake of uniqueness. I am also attempting to add a click event to an image within one of the table cell to delete the rows relating to that particular test.

My current function

function newTest(sampleID){
    var testID = $("#testCount").val();
    $("#newTest tr").clone(true)
        .addClass("test"+testID)
        .appendTo("#testsTable"+sampleID);
    $(".newdelbox:first")
        .attr("id","testDelete"+testID)
        .addClass("delbox")
        .removeClass("newdelbox");
    $(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
    testID++;
    $("#testCount").val(testID);
}

What I need to happen

Function to be called when image is clicked.

What is happening

Function is called only when script is assigned (not clicked). Function will not subsequently run when clicked. I am seeing no errors within the console.

What I have tried

chained to preceeding code:

.click(delSample(testID));
.on("click",delSample(testID));
.bind("click",delSample(testID));

As new line within function:

$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
document.getElementById("testDelete"+testID).onclick(delSample(testID));
document.getElementById("testDelete"+testID).addEventListener("click",delSample(testID),false);

i do not know of your html but i supose something like

.on("click",function(){
   var current_id = jQuery(this).attr('id');
   delSample(current_id);
});

just locate your id

try this:

 .click(function(){
  delSample(testID);
  });

OR

.on("click",function(){
   delSample(testID);
  });

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