需要提醒各位的是,上面的描述以及代碼 只是驗證自己 的想法, 不對正確性做校驗,請各位看官小心
一.想法:假如已有一個頁面,頁面有一個表格,勾選表格中的記錄,點擊修改按鈕,發起ajax get請求,通過django的views 返回form對象(後面證明無法返回一個form 對象,無奈只能返回一個 字符串)
1.在這個按鈕增加了οnclick="deleteSelect()" 觸發deleteSelect()事件
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" onclick="deleteSelect()" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
2.deleteSelect() 方法,,其中獲取name=choice,如果有被checked 的則會被加入到ids變量中,之後作爲ajax的參數,接受接口的返回
(此處是允許被批量修改的,獲取有一些問題,但是隻要實現了我的想法,剩下的可以慢慢更改)
function deleteSelect() {
var chckBox = document.getElementsByName("choice");
var num = chckBox.length
var check_res;
var ids = "";
for (var index = 0; index < num; index++) {
if (chckBox[index].checked) {
ids += chckBox[index].value + ",";
}
}
if (ids != "") {
ids = ids.substring(0, ids.length - 1); //S 刪除字符串最後一個字符的幾種方法
ids = {
'ids': ids
}
$.ajax({
type: "get",
async:false,
url: "{% url 'product:edit_product' %}", //要自行刪除的action
data: ids,
dataType: 'json',
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
$("#container").append(check_res);
$('#editMyModal').modal("show");
},
error: function (data) {
alert(data["form"]);
}
});
return check_res
} else {
alert("請選擇要刪除的記錄");
}
}
4.最初的想法是返回一個bootstrap form 對象,(form = FormProduct(instance=product)),並在前端通過{bootstrap_form form })在前端顯示,但是實驗了很多方法無法 返回一個form對象,退而其次,返回一個字符串
return HttpResponse(json.dumps({
"form": str(form)
在ajax的接收:
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
$("#container").append(check_res);
$('#editMyModal').modal("show");
}
console.log(data["form"]); 打印的結果爲
5.之後我們將這個字符串顯示在 id=editMyModal 的modal中,
此時有2個方法:
① $("#container").append(check_res); 但是如果頁面不刷新的話,則一直會在後面追加顯示,所以此方法不適用
②.document.getElementById('container').innerHTML = check_res; ,此時發現一個致命的問題,就是無法加載樣式,不管是在接口返回的時候就寫好樣式,還是接口返回之後在通過正則匹配的方式去追加樣式,都太鬧命傷財了
③.當然接口可以解析form 表單,返回json,然後通過js 獲取該json,然後加載到html框架中(循環生成一些字符串樣式(在裏面放 value 屬性),然後字符串通過 document.getElementById('container').innerHTML = check_res; )
④以上都是基於自己的一個思考過程,因爲自己代碼能力的限制,未能演示
下面的是參考別人較爲成熟方案,幫助自己實現上述的想法;
以下是完整的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自動化測試平臺</title>
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- DataTables -->
<link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/static/dist/css/AdminLTE.min.css">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="icon" type="image/png" href="/static/img/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!--產品列表-->
<div style="padding-top: 20px;padding-left: 200px ;padding-right: 200px">
<div class="col-sm-1">
<table>
<tr>
<td>
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" onclick="deleteSelect()" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
</td>
</tr>
</table>
</div>
<!-- /.box-header -->
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>產品名稱</th>
<th>產品描述</th>
<th>產品負責人</th>
<th>狀態</th>
<th>創建時間</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td><input id="radiobutton1" type="checkbox" value="{{ product.id }}" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue={{ product.id }} > {{ product.id }}</td>
<td style=' white-space: nowrap; text-overflow: ellipsis;overflow: hidden;' titlevalue={{ product.productname }}>{{ product.productname }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;" titlevalue={{ product.productdesc }}>{{ product.productdesc }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.producter }}>{{ product.producter }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.status }}> {{ product.status }}</td>
<td style=" white-space: nowrap; text-overflow: ellipsis;overflow: hidden;"titlevalue={{ product.create_time }}> {{ product.create_time }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
編輯項目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="請輸入id" >
</div>
<div class="form-group">
<label for="name">產品名稱</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="請輸入產品名稱" required>
</div>
<div class="form-group">
<label for="desc">產品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="請輸入產品描述" >
</div>
<div class="form-group">
<label for="user">產品負責人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="請輸入產品負責人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 狀態
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">關閉
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!--警告框-->
<div id="myAlert" style="display: none">
<strong>警告!</strong>編輯時只能勾選一條。
</div>
<div id="myAlert1" style="display: none">
<strong>警告!</strong>刪除時一定要勾選一條。
</div>
<!-- DataTables -->
<script>
function deleteSelect() {
var chckBox = document.getElementsByName("choice");
var check_res;
var num = chckBox.length
var ids = "";
for (var index = 0; index < num; index++) {
if (chckBox[index].checked) {
ids += chckBox[index].value + ",";
}
}
if (ids != "") {
ids = ids.substring(0, ids.length - 1); //S 刪除字符串最後一個字符的幾種方法
ids = {
'ids': ids
}
$.ajax({
type: "get",
async:false,
url: "{% url 'product:edit_product' %}", //要自行刪除的action
data: ids,
dataType: 'json',
success: function (data) {
console.log(data["form"]);
check_res=data["form"];
document.getElementById('container').innerHTML = check_res;
$('#editMyModal').modal("show");
},
error: function (data) {
alert(data["form"]);
}
});
return check_res
} else {
alert("請選擇要刪除的記錄");
}
}
//點擊全選按鈕勾選子節點操作
function demo(){
var allcheck=document.getElementById("allcheck");
var choice=document.getElementsByName("choice");
for(var i=0;i<choice.length;i++){
choice[i].checked=allcheck.checked;
}
}
//搜索或者搜索分頁後去根據select返回的value去確定第幾個option被選中
$(function(){
check();
});
//定義一個被選中的全局變量
var checkedenv_ids="{{ checkedenv_ids }}";
checkedenv_ids=checkedenv_ids.split(",");
// 根據返回值去勾選對應列
function check(){
//alert (checkedenv_ids);
//當前頁的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert(env_id);
if (checkedenv_ids.includes(String(env_id))){
$(this).attr("checked", true);
}
}
});
//全選
setAll();
}
//根據當前頁的勾選變化改變checkedenv_ids值
function change_checkedenv_ids(){
//當前頁的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert($(this).attr("checked"));
//選中則判斷數組是否存在,不存在則入棧
if ($(this).is(":checked")){
//alert(1);
//$(this).attr("checked", true);
if (!checkedenv_ids.includes(String(env_id))){
checkedenv_ids.push(String(env_id));
}
}
//未選中則判斷數組是否存在,存在則出棧
else{
if (checkedenv_ids.includes(String(env_id))){
checkedenv_ids = $.grep(checkedenv_ids, function(value) {
return value != String(env_id);
});
}
}
}
});
//alert(checkedenv_ids);
}
function setAll(){
if(!$(".checknum").checked){
$("#allcheck").prop("checked",false); // 子複選框某個不選擇,全選也被取消
}
var choicelength=$("input[type='checkbox'][class='checknum']").length;
var choiceselect=$("input[type='checkbox'][class='checknum']:checked").length;
if(choicelength==choiceselect){
$("#allcheck").prop("checked",true); // 子複選框全部部被選擇,全選也被選擇;1.對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法;2.對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
}
}
</script>
</body>
</html>
二.下面的則是藉助別人的代碼,供參考
先初始化
$(function(){
edit();
check();
});
edit 方法:其中需要關注的地方是 env[i]=env_value.attr('titlevalue'); 這個titlevalue是自定義屬性,獲取自定義屬性的值,這個在後面會有說明;還有一個地方是$('#editMyModal').modal("show"); .modal 方法是Bootstrap 模態框(Modal)插件,可以打開id=editMyModal 的模態框,後面將貼出
function edit(){
$("#edit").click(function(){
$("#myAlert").css("display","none");
$("#myAlert1").css("display","none");
var count=0;
var env_value;
var env=new Array();
var elements=$(".ipt");
$("#table").find(":checkbox:checked.checknum").each(function(){
env_value=$(this).parent()
for (var i=0;i<elements.length;i++){
env_value=env_value.next()
//alert(email_value.text());
env[i]=env_value.attr('titlevalue');
}
//alert(env)
count++;
});
if (count==1)
{
//alert(env);
for (var i=0;i<env.length-1;i++){
$(elements[i]).val(env[i]);
}
if (env[env.length-1]=="True"){
$(elements[env.length-1]).prop('checked',true);
}
else{
$(elements[env.length-1]).removeAttr('checked');
}
$('#editMyModal').modal("show");
}
else{
$("#myAlert").css("display","inherit");
}
});}
此時查看id =editMyModal 的元素,其中aria-hidden="true" 默認隱藏,在edit 方法中$('#editMyModal').modal("show"); 彈出,其中在彈框中需要顯示哪些值得,收class=ipt 的控制,因爲在edit的方法中,會獲取.ipt (var elements=$(".ipt");)
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
編輯項目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="請輸入id" >
</div>
<div class="form-group">
<label for="name">產品名稱</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="請輸入產品名稱" required>
</div>
<div class="form-group">
<label for="desc">產品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="請輸入產品描述" >
</div>
<div class="form-group">
<label for="user">產品負責人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="請輸入產品負責人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 狀態
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">關閉
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
table 的代碼如下:(在每一列都有titlevalue自定義屬性,對應edit方法中的 env[i]=env_value.attr('titlevalue');)
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>產品名稱</th>
<th>產品描述</th>
<th>產品負責人</th>
<th>狀態</th>
<th>創建時間</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue=1 > 1</td>
<td titlevalue=sdasdadasd>name</td>
<td titlevalue=desc>desc</td>
<td titlevalue=user>user</td>
<td titlevalue=True}> True</td>
<td titlevalue=今天> 今天</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="choice" class="checknum" ></td>
<td titlevalue="2" > 2</td>
<td titlevalue="name">name</td>
<td titlevalue="desc">desc</td>
<td titlevalue="user">user</td>
<td titlevalue="True"> True</td>
<td titlevalue="昨天"> 昨天</td>
</tr>
</tbody>
</table>
</div>
在此基礎上,我們需要導入一些js和css 文件,即jquer.js ,bootstrap.js 和bootstrap.css(注意導入順序)
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
其它代碼將在完整代碼中展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自動化測試平臺</title>
<script src="/static/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!--產品列表-->
<div style="padding-top: 20px;padding-left: 200px ;padding-right: 200px">
<div class="col-sm-1">
<table>
<tr>
<td>
<button id="edit" class="btn btn-block btn-warning" data-toggle="modal" >
<i class="glyphicon glyphicon-pencil">修改</i></button>
</td>
</tr>
</table>
</div>
<!-- /.box-header -->
<div class="box-body">
<table style="table-layout:fixed;" id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th><input id="allcheck" type="checkbox" onclick="demo()"/></th>
<th>ID</th>
<th>產品名稱</th>
<th>產品描述</th>
<th>產品負責人</th>
<th>狀態</th>
<th>創建時間</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="choice" class="checknum" onclick="setAll()"></td>
<td titlevalue=1 > 1</td>
<td titlevalue=sdasdadasd>name</td>
<td titlevalue=desc>desc</td>
<td titlevalue=user>user</td>
<td titlevalue=True}> True</td>
<td titlevalue=今天> 今天</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="choice" class="checknum" ></td>
<td titlevalue="2" > 2</td>
<td titlevalue="name">name</td>
<td titlevalue="desc">desc</td>
<td titlevalue="user">user</td>
<td titlevalue="True"> True</td>
<td titlevalue="昨天"> 昨天</td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="modal fade" id="editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="max-width:400px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
編輯項目
</h4>
</div>
<div class="modal-body">
<form id="container" role="form" method='POST' action="{% url 'product:edit_product' %}">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input type="text" class="ipt form-control" name="id" placeholder="請輸入id" >
</div>
<div class="form-group">
<label for="name">產品名稱</label>
<input type="text" maxlength="64" class="ipt form-control" name="productname" placeholder="請輸入產品名稱" required>
</div>
<div class="form-group">
<label for="desc">產品描述</label>
<input type="text" maxlength="200" class="ipt form-control" name="productdesc" placeholder="請輸入產品描述" >
</div>
<div class="form-group">
<label for="user">產品負責人</label>
<input type="text" class="ipt form-control" name="producter" placeholder="請輸入產品負責人" >
</div>
<div class="form-group" >
<label class="checkbox-inline">
<input type="checkbox" class="ipt" name="status" id="status"> 狀態
</label>
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">關閉
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!--警告框-->
<div id="myAlert" style="display: none">
<strong>警告!</strong>編輯時只能勾選一條。
</div>
<div id="myAlert1" style="display: none">
<strong>警告!</strong>刪除時一定要勾選一條。
</div>
<!-- DataTables -->
<script>
var check_res;
//點擊全選按鈕勾選子節點操作
function demo(){
var allcheck=document.getElementById("allcheck");
var choice=document.getElementsByName("choice");
for(var i=0;i<choice.length;i++){
choice[i].checked=allcheck.checked;
}
}
//搜索或者搜索分頁後去根據select返回的value去確定第幾個option被選中
$(function(){
edit();
check();
});
function edit(){
$("#edit").click(function(){
$("#myAlert").css("display","none");
$("#myAlert1").css("display","none");
var count=0;
var env_value;
var env=new Array();
var elements=$(".ipt");
$("#table").find(":checkbox:checked.checknum").each(function(){
env_value=$(this).parent()
for (var i=0;i<elements.length;i++){
env_value=env_value.next()
//alert(email_value.text());
env[i]=env_value.attr('titlevalue');
}
//alert(env)
count++;
});
if (count==1)
{
//alert(env);
for (var i=0;i<env.length-1;i++){
$(elements[i]).val(env[i]);
}
if (env[env.length-1]=="True"){
$(elements[env.length-1]).prop('checked',true);
}
else{
$(elements[env.length-1]).removeAttr('checked');
}
$('#editMyModal').modal("show");
}
else{
$("#myAlert").css("display","inherit");
}
});}
//定義一個被選中的全局變量
var checkedenv_ids="{{ checkedenv_ids }}";
checkedenv_ids=checkedenv_ids.split(",");
// 根據返回值去勾選對應列
function check(){
//alert (checkedenv_ids);
//當前頁的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert(env_id);
if (checkedenv_ids.includes(String(env_id))){
$(this).attr("checked", true);
}
}
});
//全選
setAll();
}
//根據當前頁的勾選變化改變checkedenv_ids值
function change_checkedenv_ids(){
//當前頁的列id
$("#table").find(":checkbox.checknum").each(function(){
env_id=$(this).parent().next().text();
if (env_id != "") {
//env_ids.push(env_id);
//alert($(this).attr("checked"));
//選中則判斷數組是否存在,不存在則入棧
if ($(this).is(":checked")){
//alert(1);
//$(this).attr("checked", true);
if (!checkedenv_ids.includes(String(env_id))){
checkedenv_ids.push(String(env_id));
}
}
//未選中則判斷數組是否存在,存在則出棧
else{
if (checkedenv_ids.includes(String(env_id))){
checkedenv_ids = $.grep(checkedenv_ids, function(value) {
return value != String(env_id);
});
}
}
}
});
//alert(checkedenv_ids);
}
function setAll(){
if(!$(".checknum").checked){
$("#allcheck").prop("checked",false); // 子複選框某個不選擇,全選也被取消
}
var choicelength=$("input[type='checkbox'][class='checknum']").length;
var choiceselect=$("input[type='checkbox'][class='checknum']:checked").length;
if(choicelength==choiceselect){
$("#allcheck").prop("checked",true); // 子複選框全部部被選擇,全選也被選擇;1.對於HTML元素我們自己自定義的DOM屬性,在處理時,使用attr方法;2.對於HTML元素本身就帶有的固有屬性,在處理時,使用prop方法。
}
}
</script>
</body>
</html>