当我在分页中使用.load()ajax/jquery时,我在这里遇到了一个问题。当我转到另一个页面时,复选框的状态将不会保留。例如,我在第1页中选中了2个项目,然后当我转到第2页选择另一个项目时,然后当返回第1页测试我选中的项目是否保持选中状态时。不幸的是,它被取消选中了,可能是因为.load()。如果有其他选择可以使用side.load()来保持我的复选框处于选中状态,请帮助我。
这是我为.load()ajax编写的代码:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');});
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active');
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$('body').on('click', '.paginate_click', function(e){
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
});
</script>
嗨@charleshaa它不起作用这就是我对我的脚本所做的
这是我的复选框代码
echo "<div id='a'><input type='checkbox' class='tick' name='items[$i]' id='$i' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
怎么了??我急需帮助
您需要在变量中保留复选框,以便在加载后重新检查它们。
首先在复选框class="tick"
中添加一个类。
那么你会:
$(".paginate_click").click(function (e) {
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
编辑:
此外,最好不要使用.click()
表示法,而是应该始终使用.on()
在这个例子中,你可以这样写:
$('body').on('click', '.paginate_click', function(e){
//code
});
它的性能要好得多,因为它只将一个事件侦听器附加到主体,而不是将一个附加到每个.paginate_click
。
查看我对唯一ID的评论,你应该可以离开了。