Django前端HTML通过JS实现表格可编辑,动态添加行,回车完成新建文件夹

匿名 (未验证) 提交于 2019-12-02 20:32:16

功能描述:

点击“新建文件夹”按钮,在table的末尾增加一行;单击页面的新增行,使单元格td变成可编辑状态;输入内容后,当单元格失去焦点时,保存输入的内容;回车后通过AJAX提交后台完成新建文件夹。

HTML部分代码,id="table2"和EditType="TextBox"后面需要用到。

<button class="btn btn-default" type="button" id="create_dir" name="create_dir" value="create_dir" style='margin-left:10px;margin-right:10px;color:rgb(60, 141, 188);' onclick="AddRow($('#table2')[0],1)">新建文件夹</button>  <table id="table2" class="table table-hover" style="overflow: auto;" > <tr> <td class='th3' EditType="TextBox">                        <img src="/static/img/file4_24.ico">&nbsp;&nbsp;&nbsp;                        {% if fileinfo.search_flag == 0 %}                        {{ fileinfo.file_name }}                        {% else %}                        {{ fileinfo.file_path }}                        {% endif %}                     </td> </tr>

样式表格td部分,新增行改一下:

{% block style %}  <style>     td{       border-bottom-width: 1px;       border-bottom-style: solid;       border-bottom-color: #CCCCCC;       }       .EditCell_TextBox {       width: 90%;       border:1px solid #0099CC;       }       .EditCell_DropDownList {       width: 90%;       } </style> {% endblock  %}

JS部分,也是最关键的一部分:

 

JS部分根据自己的需求优化了一下:

1.EditTables()设置多个表格不要了,我只需要编辑新增行就行了。而且innerHTML会被看到td中代码。

2.tabProduct获取自己table的id。

3.新增按钮onclick="AddRow($('#table2')[0],1)",参数为自己表对象,注意[0]。AddRow中可以改新增行默认内容,我的为“新建文件夹”。

4.SetRowCanEdit()函数中增加如下代码,使新增行后直接处于可编辑状态,也可以单击进入编辑状态。

EditCell(row.cells[j]);

5.CreateTextBox()中获取用户输入的值,AJAX提交后台:

textBox.onkeypress = function(event){         if (event.keyCode == "13"){           $.ajax({               url:"/create_dir?dir_name="+this.value,               type:"GET",               data:'',    //               processData:false,               contentType:false,               success:function (data) {                 // alert("创建文件夹完成!");                 history.go(0);               }           });         }        }

6.python实现新建文件夹:

def create_dir(request):     if request.method == 'GET':         dir_name = request.GET.get('dir_name')         print('create_dir:'+dir_name)         path = os.path.join(current_path,dir_name)         while os.path.exists(path):             path += '-副本'         os.makedirs(r'%s'%path)         return HttpResponse(path)     else:         return HttpResponse("error")

7.最后,效果如下:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!