简体   繁体   中英

Best way to execute external Javascript function from HTML element's onclick event returned from an Ajax call

index.php:

<html>
    <head>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="box"></div>
        <div onclick="getContent()">Open Window</div>
    </body>
</html>

script.js:

function getContent() {
    //ajax call that returns the html from content.php and places it in the box div
}
function sayHello() {
    console.log('Hello');
}
function sayGoodBye() {
    console.log('Good Bye');
}

content.php:

<div onclick="sayHello()">Say Hello</div>
<div onclick="sayGoodBye()">Say Good Bye</div>

What is the correct way to make the functions sayHello() and sayGoodBye() work? Currently they do nothing.

As your element comes from ajax and append to #box dynamically, so you need an delegate event handling.

$('#box').on('click', '#newElement', function() {

});

Syntax for delegate of .on() is:

$(container).on(eventName, target, handlerFunction);

To trigger you need to use

$('#box div').eq(0).click(); // sayHello()

$('#box div').eq(1).click(); // sayGoodBy()

NOTE

I think it should work normally

Look here

And its also possible to trigger those click events

Check this

Please keep file index.php, script.js, content.php in the same folder.

index.php

<html>
    <head>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="box"></div>
        <div onclick="getContent()">Open Window</div>
    </body>
</html>

script.js

function getContent() {
    //ajax call that returns the html from content.php and places it in the box div
    $.ajax({
        url: 'content.php',
        success: function(data) {
            $('#box').html(data);
        }
    });
}

function sayHello() {
    console.log('Hello');
}

function sayGoodBye() {
    console.log('Good Bye');
}

content.php

<?php

$strContent="";
$strContent.="<div onclick='sayHello()'>Say Hello</div>";
$strContent.="<div onclick='sayGoodBye()'>Say Good Bye</div>";

?>

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