首页 > 解决方案 > 如何从 jQuery 中的兄弟 div 元素中检索一些文本

问题描述

我按以下顺序在页面上有一些 div。当有人单击 UL .list-links 中的链接时,我想捕获

<span class="asa_portlet_title">Title here</span>

在一个变量中。我试过使用兄弟姐妹和最接近的,但它总是返回空。

--

<div class="my_portlet" style="display:none;">
    <span class="asa_portlet_title">Title here</span>
</div>

<div class="links">
    <div class="">
        <ul class="list-links">
            <li class="margin-bottom-medium">
                <a href="linkhere.html" target="_self">Link name</a> 
                <a href="linkhere.html" target="_self">Link name</a> 
                <a href="linkhere.html" target="_self">Link name</a> 
                <a href="linkhere.html" target="_self">Link name</a> 
            </li>
        </ul>
    </div>  
</div>

--

$('[ul.list-links a').click(function() {
    var _portletTitle = $(this).siblings('.my_portlet').text(); 
});

也可以使用纯 javascript 方法。基本上我在包含链接的页面上有许多 div,这些 div 在其上方有另一个 div,其中存在标题

有人能把一个小的工作样本放在一起吗?

标签: javascriptjquery

解决方案


您不是在尝试获取兄弟姐妹,而是在尝试.links获取this.

您还必须阻止 a 元素的默认操作。您可以通过调用preventDefault()事件对象来做到这一点。

$('ul.list-links a').click(function(event) {
  event.preventDefault();
  var _portletTitle = $(this).closest('.links').prev('.my_portlet').text();
  console.log(_portletTitle);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my_portlet" style="display:none;">
  <span class="asa_portlet_title">Title here</span>
</div>

<div class="links">
  <div class="">
    <ul class="list-links">
      <li class="margin-bottom-medium">
        <a href="linkhere.html" target="_self">Link name</a>
        <a href="linkhere.html" target="_self">Link name</a>
        <a href="linkhere.html" target="_self">Link name</a>
        <a href="linkhere.html" target="_self">Link name</a>
      </li>
    </ul>
  </div>
</div>

<div class="my_portlet" style="display:none;">
  <span class="asa_portlet_title">Title here 2</span>
</div>

<div class="links">
  <div class="">
    <ul class="list-links">
      <li class="margin-bottom-medium">
        <a href="linkhere.html" target="_self">Link name 2</a>
        <a href="linkhere.html" target="_self">Link name 2</a>
        <a href="linkhere.html" target="_self">Link name 2</a>
        <a href="linkhere.html" target="_self">Link name 2</a>
      </li>
    </ul>
  </div>
</div>


推荐阅读