繁体   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:

<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>

使sayWello()和sayGoodBye()函数正常工作的正确方法是什么? 目前,他们什么也没做。

由于您的元素来自ajax并动态追加到#box ,因此您需要委托事件处理。

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

});

.on()委托的语法是:

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

要触发,您需要使用

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

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

注意

我认为应该可以正常工作

看这里

而且还可以触发那些点击事件

检查一下

请将文件index.php,script.js,content.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

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>";

?>

暂无
暂无

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

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