javascript - 如何从 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,其中存在标题
有人能把一个小的工作样本放在一起吗?
解决方案
您不是在尝试获取兄弟姐妹,而是在尝试.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>
推荐阅读
- jekyll - Jekyll:对一些集合进行分组,但不是全部
- node.js - express.static() 和 sendFile() 问题...用nodejs创建动态主机
- python - 如何加快此文件创建过程?
- vhdl - 在 std_logic_vector 的变量上左移或右移
- laravel - 使用 Webpack/Laravel 混合将 CKEditor 转换为 ES5
- angular - Angular 6 迁移问题
- python-3.x - 使用 python 3 将 .csv 文件导入 sqlite3 时遇到问题
- tensorflow - 无法转换类型的对象
张量 - docker - 码头工人登录詹金斯
- r - 在 R Markdown 中导出为 PDF 时如何修复“找不到函数 read.socrata”