以下是我的HTML:
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>我想使用jquery清除span的文本(如果有的话)。我已经写了密码:
$('#file-7').on('change', function(){
var spn = $(this).closest('span');
spn.attr('text','');
});文本不会被删除。我做错了什么?
发布于 2018-03-14 06:44:00
$('#file-7').on('change', function(){
var spn = $(this).closest('.box').find('span');
spn.text('');
});解释:,您必须找到最近的父元素,它的跨度是您试图替换文本的范围。在这里,父程序是.box &然后在其中找到span。
你犯的第二个错误是$(spn).attr('text','');。这里不需要$(),也不需要使用attr()。你可以像spn.text('');一样简单
为您提供工作样本:
$('#file-7').on('change', function(){
var spn = $(this).closest('.box').find('span');
spn.text('');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>
发布于 2018-03-14 06:40:57
你只需要这么做
spn.html('');我们不需要用变量编写$()
发布于 2018-03-14 06:48:49
您可以在jQuery中用文本函数替换文本。并且您有一个错误,您的变量是spn,但是您使用它作为$(spn)。
$('#file-7').on('change', function(){
var spn = $(this).next('label').find('span');
spn.text('');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>
https://stackoverflow.com/questions/49271170
复制相似问题