当我单击“取消”按钮时,我想隐藏最近的“..my file”类。我正在尝试这样做:
<div>
<label for="file">file</label>
<input type="file">
<a href="#" class="my-file">first file</a>
<button class="cancel-button" type="button">Cancel</button>
</div>
<div>
<label for="file">file</label>
<input type="file">
<a href="#" class="my-file">Second file</a>
<button class="cancel-button" type="button">Cancel</button>
</div>$(function() {
$('.cancel-button').on('click', function () {
alert('works');
$(this).closest('.my-file').hide();
$(this).closest('a').hide();
})
})当我单击“取消”按钮时,会收到警报,但隐藏不起作用。我在这里错过了什么?
发布于 2016-04-04 09:35:49
closest()用于查找父元素。.my-file是.cancel-button的兄弟,所以您应该使用siblings()。
$('.cancel-button').on('click', function() {
$(this).siblings('.my-file').hide();
});如果您可以保证.my-file总是直接出现在HTML中的.cancel-button之前,那么您可以使用prev()方法:
$(this).prev().hide();发布于 2016-04-04 09:36:46
closest()用于查找层次结构上的父元素,而使用prev(),如下所示:
$(function() {
$('.cancel-button').on('click', function () {
$(this).prev('a.my-file').hide();//OR $(this).prev().hide();
});
});https://stackoverflow.com/questions/36399048
复制相似问题