我的网站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>
答案 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;
});