我有一个类似这样的 html 页面:
<div class="list-group-item" style="border-left: none; border-right: none;">
<img src="./img/desktop.png" height="25" width="25">
<a class="a-file">testcase.txt</a>
<button class="btn btn-default btn-sm btn-current" style="float: right;">
<span class="glyphicon glyphicon-ok-circle span-current"></span>
</button>
<button class="btn btn-default btn-sm btn-star" style="float: right;">
<span class="glyphicon glyphicon-star-empty span-star"></span>
</button>
</div>
我想获取 <a>
中的文件名当用户单击其中一个按钮时。我试过这样做但它不起作用:
$(document).on('click','.btn-current',function(){
var file = $('.btn-current').closest('.a-file').text();
alert(file);
});
最佳答案
.closest()
仅搜索父项,因此您可以转到父项 list-group-item
,然后您可以使用 找到子项。 child ()
。最好使用 id
在 DOM 中搜索,因为它有索引并且搜索速度更快。
$(document).on('click', '.btn-current', function() {
var file = $('.btn-current').closest('.list-group-item').children('.a-file').text();
console.log(file);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group-item" style="border-left: none; border-right: none;">
<img src="./img/desktop.png" height="25" width="25">
<a class="a-file">testcase.txt</a>
<button class="btn btn-default btn-sm btn-current" style="float: right;"><span class="glyphicon glyphicon-ok-circle span-current">btn-current</span></button>
<button class="btn btn-default btn-sm btn-star" style="float: right;"><span class="glyphicon glyphicon-star-empty span-star"></span></button>
</div>
关于javascript - 单击按钮获取最近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50460721/