我按以下顺序在页面上有一些 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句