Sunday 24 December 2017

javascript - Click on dynamically created HTML elements using JQuery

style="font-weight: bold;">

Answer



style="font-weight: bold;">

Answer







I want to
be able to click on a element I've dynamically created and create an alert, and I can't
seem to figure it out. I've looked at a bunch of similar threads on how to use .on, but
I can only get it to work for static elements. Thanks in
advance!



            id="about">About

id="lhn">




And
JavaScript:



$(document).ready(function
() {

$("#about").click(function () {


$("#lhn").append(" id='#child'>Child
");



$("#lhn").on("click", "#child", function () {
alert("Child has been
clicked");
});


});

});


Answer




Bind the event outside your
about click handler. also, your ID should be
child not #child when creating the
element:




$(document).ready(function()
{
$("#lhn").on("click", "#child", function () {
alert("Child has
been clicked");
});

$("#about").click(function ()
{
$("#lhn").append("
Child
");

});
});



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...