加载AJAX的内容使用.ON或在ajax请求页面中添加脚本?

时间:2015-11-09 15:14:02

标签: jquery ajax

我的网站view more页面中有一个index选项,我使用AJAX加载。 这将为page_ajax.php的用户带来更多内容。

问题是此DOM内容需要JQUERY点击事件。

<span class=productinfo>product info</span>

我的问题是,我应该在哪里添加<script>标签?在index.php页面或page_ajax.php中(将在每次调用中加载jquery)?

如果我在index.php中添加jquery将无效,我应该在page_ajax.php中添加脚本标记吗?或我应该在索引jquery中使用.ON 吗?怎么会这样?有人可以举个例子吗?

<script>
$(function() {
$(".productinfo").click(function(){

var element = $(this);
var I = element.attr("data-id");
var info = 'id=' + I;

 $.ajax({
   type: "POST",
   cache: false,
   url: "/product.php",
   dataType: "json",
   data: info,

  success: function(data) {
    alert(data);
  }

 });
return false;
});
});
<script>

1 个答案:

答案 0 :(得分:1)

这些元素是动态加载的,因此jQuery在委派该处理程序时不会知道它们。

所以你必须将事件委托给这样的父母:

$( document.body ).on('click', '.productinfo' , function(e){

    var element = $(this);
    var I = element.attr("data-id");
    var info = 'id=' + I;

    $.ajax({
        type: "POST",
        cache: false,
        url: "/product.php",
        dataType: "json",
        data: info,

        success: function(data) {
            alert(data);
        }

    });

    return false;

});