
本文旨在解决在使用 Bootstrap 4 的文件上传组件时,动态添加的 input[type=”file”] 元素无法显示所选文件名的问题。我们将通过事件委托的方式,确保即使是动态添加的 input 元素也能正确显示文件名。
在使用 Bootstrap 4 的文件上传组件时,我们经常需要动态地添加 input[type=”file”] 元素。然而,直接使用 jQuery 的 change() 方法绑定事件,通常只能对页面加载时就存在的元素生效,对于动态添加的元素则无效。 这是因为事件绑定发生在元素创建之前。 为了解决这个问题,我们需要使用事件委托。
事件委托
事件委托的核心思想是将事件监听器绑定到一个静态的父元素上,然后利用事件冒泡的机制,当子元素触发事件时,父元素也能监听到。 这样,即使子元素是动态添加的,也能触发父元素上的事件监听器。
实现步骤
- 选择一个静态父元素: 找到一个在页面加载时就存在的父元素,并且该父元素包含所有动态添加的 input[type=”file”] 元素。在本例中,可以选择 id=”image_box” 的 div 元素。
- 使用 on() 方法绑定事件: 使用 jQuery 的 on() 方法,将 change 事件绑定到父元素上,并指定事件触发的目标元素为 input[type=”file”]。
- 获取文件名并更新标签: 在事件处理函数中,获取所选文件的文件名,并更新对应的 <label class=”custom-file-label”> 标签的文本内容。
代码示例
以下是修改后的 JavaScript 代码:
var total_image = 1;
//add more images for products
function add_more_images() {
total_image++;
var html = '<div class="form-group" id="add_image_box' + total_image + '"><label>Image</label><div class="input-group form-group" ><div class="custom-file"><input type="file" name="image[]" accept="image/*" class="custom-file-input changeme" id="exampleInputFile" required><label class="custom-file-label" for="exampleInputFile">Choose Image...</label></div> <div class="input-group-append"><button class="btn btn-danger" type="button" onclick=remove_image("' + total_image + '")>Remove Image</button></div></div></div>';
jQuery('#image_box').append(html); // 使用 append 而不是 after
}
$(document).ready(function() {
$('#image_box').on('change', 'input[type="file"]', function(e) {
var fileName = e.target.files[0].name;
// change name of actual input that was uploaded
$(this).next().html(fileName);
});
});
登录后复制
代码解释
- jQuery(‘#image_box’).append(html);: 使用 append() 将新的 HTML 代码添加到 id=”image_box” 的 div 元素内部,而不是使用 after() 将其添加到外部。这样,动态添加的 input[type=”file”] 元素仍然是 id=”image_box” 的子元素,可以触发事件委托。
- $(‘#image_box’).on(‘change’, ‘input[type=”file”]’, function(e) { … });: 将 change 事件绑定到 id=”image_box” 的 div 元素上,并指定事件触发的目标元素为 input[type=”file”]。当任何 input[type=”file”] 元素(包括动态添加的)触发 change 事件时,该事件处理函数将被执行。
- $(this).next().html(fileName);: 在事件处理函数中,$(this) 指的是触发事件的 input[type=”file”] 元素。$(this).next() 获取的是紧随其后的 <label class=”custom-file-label”> 元素,然后使用 html() 方法更新其文本内容为所选文件名。
注意事项
- 确保在 HTML 中已经包含了 jQuery 库。
- 确保在 document.ready 事件中执行事件委托代码,以确保页面加载完成后再绑定事件。
- Bootstrap 4 的文件上传组件需要特定的 HTML 结构才能正常工作,请参考 Bootstrap 4 的官方文档。
总结
通过使用事件委托,我们可以轻松地解决动态添加的 input[type=”file”] 元素无法显示所选文件名的问题。 这种方法不仅适用于 Bootstrap 4 的文件上传组件,也适用于其他需要动态添加元素的场景。 掌握事件委托,可以提高代码的灵活性和可维护性。
以上就是Bootstrap 4:动态添加的文件上传Input显示文件名的详细内容,更多请关注php中文网其它相关文章!
相关标签:


