当按钮从ajax调用时,jquery不起作用

时间:2015-02-24 22:13:54

标签: javascript php jquery ajax

page1.php中

<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>

(我有相同的功能按钮,但不同的ID)

当他们从ajax的页面加载它不起作用时

使page2.php

<html>
<input type="button" id="reload">
<div id="box">
<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>
</div>
<script>
    $(".Clic_function").click(function () {
        alert("Hi");
    });

  $("#reload").click(function () {
        $.ajax({
            url: "Page1.php",
            context: document.body,
        }).then(function (result) {
            $("#reload").html(result);
         }
   });
</script>
</html>

仅在第一次工作但是当重新加载脚本(警报)不再工作时,我可以看到页面加载正常但脚本没有。

2 个答案:

答案 0 :(得分:1)

您需要使用事件委派并将事件附加到更高级别的DOM。我将它附加到示例中的document

$(document).on('click', '.Click_function', function(){
    alert("Hi");
});

答案 1 :(得分:1)

您需要将click事件委派给第一次运行页面时存在的内容 -

$(document).on('click', ".Clic_function", function () {
     alert("Hi");
});

jQuery在运行时只知道页面中的元素,因此添加到DOM的新元素无法被jQuery识别。为了解决这个问题,请使用event delegation,将新添加的项目中的事件冒泡到jQuery在页面加载时运行时的DOM中的某个点。许多人使用document作为捕捉泡沫事件的地方,但是在DOM树上走高的位置并不是必需的。理想情况下you should delegate to the nearest parent that exists at the time of page load.