gpt4 book ai didi

javascript - 使用 jquery 如何获取父 LI,其中 LI 的文本与我的按钮文本相匹配?

转载 作者:行者123 更新时间:2023-12-03 01:25:33 27 4
gpt4 key购买 nike

当我单击按钮时,我想从列表中获取 li,然后触发一个事件,就像单击 li 本身一样。换句话说,我正在尝试从按钮触发菜单上的单击事件。

下面的代码返回文档对象而不是父 LI。

写在这里:https://codepen.io/GerdSuhr/pen/WKZLYQ?editors=1011

$('#switch button').on('click', function(){
var text = $(this).text();
var myLI = $('dl-menu li a span:contains(text)').parent().parent();
console.log(myLI);
//$(myLI).trigger('click.dl-menu');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul class="dl-menu">
<li><a href=""><span>aero</span></a></li>
<li><a href=""><span>bio</span></a></li>
<li><a href=""><span>lab</span></a></li>
</ul>

<br>
<br>
<br>

<div id="switch">
<button>bio</button>
</div>

最佳答案

你的逻辑已经差不多了,你只需要将 text 变量的值连接到选择器中,然后引发点击事件:

$('#switch button').on('click', function() {
var text = $(this).text();
var $myLI = $(`.dl-menu li a span:contains(${text})`).closest('li');
$myLI.click();
});

$('li').click(function() {
console.log(`You clicked the ${$(this).text()} <li> element`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul class="dl-menu">
<li><a href=""><span>aero</span></a></li>
<li><a href=""><span>bio</span></a></li>
<li><a href=""><span>lab</span></a></li>
</ul>

<br /><br /><br />

<div id="switch">
<button>bio</button>
</div>

另请注意,与链式 parent() 调用相比,首选使用 closest()

关于javascript - 使用 jquery 如何获取父 LI,其中 LI 的文本与我的按钮文本相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564157/

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