在我下面的代码中,当我选择一个复选框时,它会显示选中项目的名称。但我现在的问题是,表格是分页的,所以当我移至下一页并返回时,已经选中的项目返回未选中状态。 当我选中一个框并使用 ajax 请求进行过滤时,这同样适用,当我返回时,已经选中的框将移至未选中状态。
如何隐藏表格页来解决这个问题?
HTML
<table class="table" id="table" style="background-color:white" >
<thead>
<tr>
<th></th>
<th colspan="5"></th>
<th></th>
</tr>
</thead>
<tbody>
@foreach($items as $item)
<tr>
<td><input onclick="return results(this)" data-item="{{$item->toJson()}}" type="checkbox" id="{!! $item->id !!}" name="{!! $item->name !!}" value="{!! $item->price !!}" /> </td>
<td>{{$item->name }}</td>
</tr>
@endforeach
</tbody>
</table>
{{$items->links()}}
JS
function results(item){
var major = JSON.parse(item.dataset.item);
if(item.checked == true) {
$('.panel').append(
'<div class="container "> '+
'<table style="width:100%;" class="table" id="tables">'+
'<thead>'+'<thead>'+
'<tbody>'+
'<tr>'+ '<td class="name" >'+major.name+'</td>'+] '</tr>'+
'</tbody>'+'</table>'+'</div>')}
} else {
});
}
}
}
AJAX
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
table.html("");
$.each(data, function(idx, elem){
table.append(
"<tr><td><input type='checkbox' onclick='return results(this)' data-item='"+JSON.stringify(elem)+"' id='"+elem.id+"' name='"+elem.name+"' value='"+elem.price+"' data-id="+elem.id+" /></td><td >"+elem.name+"</td><tr>"
);
});
}
最佳答案
可以通过 “JavaScript - localStorage”
功能保存状态。
今天的浏览器有能力保存比 cookies 更“干净”和信息丰富的信息。
在“复选框”元素上,我将添加事件监听器,该监听器将启动名为 “saveState()”
的函数。在此函数中,我将保存有关复选框的信息。
function saveState()
{
localStorage.setItem("checkBoxStatus", "Checked");
}
此信息保存在浏览器的存储空间中,除非您自行删除,否则不会被删除。 要删除它,您有两种选择:
`localStorage.removeItem("checkBoxStatus");`
`localStorage.clear();`
然后,当您再次重新进入该页面时,在“构建” View 时,您可以添加小函数,将状态设置为“已保存”状态。
function resumeState()
{
if(localStorage.getItem("checkBoxStatus") === "Checked)
//get check box and check or uncheck
}
如何使用存储的数据
这是我的观点,但我更喜欢通过 JavaScript
构建我的 HTML View ,因为我发现它更简洁,也更容易,因为今天你经常与“JavaScript/Ajax”
功能,需要更高的响应能力。
所以我会用 JavaScript Dom 构建我的整个 View **
function buildView()
{
var element = document.createElement("div");
var checkBox = document.createElement("input");
checkBox.settAttribute("type", "checkbox");
//here we will check
localStorage.getItem("checkBoxStatus") === "Checked" ? checkBox.setAttribute("checked", "true") : checkBox.setAttribute("checked", false);
element.appendChild(checkBox);
document.body.appendChild(element);
}
**
或使用 setTimeout
函数并坚持使用“HTML
” View :
<body onload='setTimeout(buildView(), 2000);>'
这将等到所有 views
都构建完成并在它之后开始。
您可以根据在“onload
”事件期间加载的数据量来设置正确的时间。如果是小数据,你甚至可以等待 1 秒 -> 1000
function buildView()
{
var checkBox = document.getElementById("checkBox");
//here we will check
if(localStorage.getItem("checkBoxStatus") === "Checked")
{
checkBox.setAttribute("checked", "true");
}
else
{
checkBox.setAttribute("checked", false);
}
}
记住这里主要是使用localStorage功能来保存数据,之后如何使用这些数据,完全取决于开发者的想象力和创造力
关于javascript - 在javascript中隐藏表格页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906001/