gpt4 book ai didi

javascript - 如何从 jQuery 中的同级 div 元素检索一些文本

转载 作者:行者123 更新时间:2023-12-01 00:46:31 25 4
gpt4 key购买 nike

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

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

在变量中。我尝试过使用 sibling 和最接近的,但它总是返回空。

--

<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,其中标题存在

有人能够组装一个小型工作样本吗?

最佳答案

您并不是试图获取同级,而是尝试获取 this 的父级 .links 的同级。

此外,您还必须防止 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>

关于javascript - 如何从 jQuery 中的同级 div 元素检索一些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57293847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com