javascript - 单击按钮获取最近的元素

标签 javascript jquery html css twitter-bootstrap-3

我有一个类似这样的 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/

相关文章:

javascript - 如何使 Javascript/JQuery 对象方法可在整个 HTML 页面中访问

php - 无法添加或更新子行

javascript - 使用 jQuery.load();在使用 href 作为参数时仅加载文档的一部分

html - Bootstrap : image height decrease while resizing window

javascript - 从 url 获取 php 输出

javascript - 错误 : Data should not be empty or the "fields" option should be included

javascript - CSS3 动画图像质量规模

javascript - 自动修复或自动更正 ESLint 规则的任何解决方案?

javascript - 如何使用 node.js 中的 nodemailer 和请求模块将图像附加到来自 URL 的电子邮件?

jquery - 我该如何做到这一点,当人们将我的移动网站保存到他们的主屏幕时,它会像 Kahoot.it 一样删除 Safari?