简体   繁体   English

从Ajax调用返回的HTML元素的onclick事件中执行外部Javascript函数的最佳方法

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

index.php: 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: 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: 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? 使sayWello()和sayGoodBye()函数正常工作的正确方法是什么? Currently they do nothing. 目前,他们什么也没做。

As your element comes from ajax and append to #box dynamically, so you need an delegate event handling. 由于您的元素来自ajax并动态追加到#box ,因此您需要委托事件处理。

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

});

Syntax for delegate of .on() is: .on()委托的语法是:

$(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,script.js,content.php保留在同一文件夹中。

index.php 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 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 content.php

<?php

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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