作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在页面上有一些 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/
我是一名优秀的程序员,十分优秀!