Javascript 更改多个输入的标签文本

Javascript 更改多个输入的标签文本,javascript,jquery,input,jquery-selectors,Javascript,Jquery,Input,Jquery Selectors,我有一个动态页面,可以有许多输入[type=“file”]字段。一旦选择了一个文件,我需要更改每个输入的标签 因此,对于每个输入,如果: 空:text=“上传” 所选文件:text=文件名 下面是一个HTML示例: <label for="upload-qm1"> <span class="button">upload</span> <input id="upload-qm1" type="file" accept=".pdf, .d

我有一个动态页面,可以有许多
输入[type=“file”]
字段。一旦选择了一个文件,我需要更改每个输入的标签

因此,对于每个输入,如果:

  • 空:text=“上传”
  • 所选文件:text=文件名
下面是一个HTML示例:

<label for="upload-qm1">
    <span class="button">upload</span>
    <input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>
但是,我不知道我的页面上会有多少
input
字段。我试过这样的方法:

$(this).parent('label').find('span').text($(this).val());

但不幸的是,它不起作用。关于如何获得更改所有
输入
字段的方法的任何帮助?

您可以使用DOM遍历查找与已更改的
输入
相关的
span
。试试这个:

$('input:file').change(function() {
    $(this).prev('span').text($(this).val());
})

您可以使用DOM遍历来查找与已更改的
输入相关的
span
。试试这个:

$('input:file').change(function() {
    $(this).prev('span').text($(this).val());
})

您尝试的大部分代码都是正确的。 问题是您为
parent()
函数设置了一个参数

试着这样做:
$(this).parent('label').find('span').text($(this.val())

还要确保
$(this)
是输入字段,而不是标签本身,
如果您单击标签
$(此)
就是标签。

您尝试的大部分代码都是正确的。 问题是您为
parent()
函数设置了一个参数

试着这样做:
$(this).parent('label').find('span').text($(this.val())

还要确保
$(this)
是输入字段,而不是标签本身, 如果您单击标签
$(此)
就是标签。

$('input[type=“file”]”)。在('change',function()上{
id=$(this.attr('id');
console.log(“更改事件”)
var file=$('\'+id).val().split('\\').pop();
如果(文件!=''){
$('label[for=“”+id+”]span')。文本(文件)
} 
});

上传
$('input[type=“file”]”)。在('change',function()上{
id=$(this.attr('id');
console.log(“更改事件”)
var file=$('\'+id).val().split('\\').pop();
如果(文件!=''){
$('label[for=“”+id+”]span')。文本(文件)
} 
});

上传