javascript - JS 应该在页面重新加载后保持它的工作
问题描述
我在 JS 中基本上是零,所以这个问题可能完全是愚蠢的,无论如何……我有一个脚本,在 bootstrap4 文件输入中显示文件名
https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input
该脚本负责在输入中显示文件名:
问题是当页面重新加载时(例如,由于表单验证失败),该字段将自身变为空,即其中没有文件名。是否可以修改此脚本以在页面重新加载后显示文件名?PS文件在重新加载后在那里。他们由后端兑现。文件输入 html 代码如下 {% endif %}
<script>
$(document).on('change', '.custom-file-input', function (event) {
$(this).next('.custom-file-label').html(event.target.files[0].name);
})
</script>
{% if widget.is_initial %}
<a href="{{ widget.value.url }}"><img class="ml-0" src="{% thumbnail widget.value "small" %}"></a>
{% if not widget.required %}
{% endif %}
<br>
{% endif %}
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="{{ widget.type }}" name="{{ widget.name }}" class="custom-file-input" id="inputGroupFile02" id="inputGroupFile02" aria-describedby="inputGroupFileAddon01" {% include "django/forms/widgets/attrs.html" %}>
<label class="custom-file-label " for="inputGroupFile02">{{ widget.value|default_if_none:"Choose the file" }} {{ widget.filename }}</label>
</div>
</div>
解决方案
首先,您没有显示整个代码、完整形式和后端视图。根据我的理解,如果您想在页面重新加载后保留文件名,我可以建议您。您将其存储在视图中的会话中,如下所示:
request.session['file']=reques.FILES
在您的模板中,您可以像这样获取此会话变量,以将其放在文件名的位置:
{{request.session.file}}
推荐阅读
- featuretools - 如何使用功能工具 get_pandas_data_slice
- sql - COUNT(INVOICE.INV_NUM) 在两个不同的场景中给出不同的答案
- r - x 轴上具有多个逻辑变量的堆积条形图
- javascript - svg 倾斜矩阵/变换而不挤压线条
- html - 删除上边距引导程序 4 导航栏
- excel - excel:索引和数学公式,将从匹配中提取整行数据。
- javascript - 使用 vanilla JS,使用模板文字循环遍历对象数组,并将数组作为道具
- c - 在 C 二叉搜索树中查找和删除中位数
- scala - class(val a: Int) 和 class(a: Int) 有什么区别?
- r - 如何在数据框中用正确的纬度和经度替换 NA?