gpt4 book ai didi

javascript - jQuery .closest() 不选择最近的元素

转载 作者:可可西里 更新时间:2023-11-01 13:08:37 26 4
gpt4 key购买 nike

出于某种原因,我在选择另一个元素上方的元素时遇到了问题。我想选择位于 .discount-type 类之上的最近的 .discount-dropdown 类。我做错了什么?

HTML(多个):

<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle discount-dropdown" data-toggle="dropdown" aria-expanded="false">$ <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right adjustment-dropdown" role="menu">
<li><a class="discount-type">$</a></li>
<li><a class="discount-type">%</a></li>
</ul>
</div>

jQuery:

$('.discount-type').on('click', function(event){
$sign = $(this).html().substr(0,1);
$parentElement = $(this).closest('.discount-dropdown').html(); //this isn't working
$newHtml = $sign + $parentElement.substr(1);
alert($newHtml);
});

enter image description here

最佳答案

因为按钮不是 li 的父级

$('.discount-type').on('click', function(event){
$sign = $(this).html().substr(0,1);
$parentElement = $(this).closest('ul').prev('.discount-dropdown').html(); //this isn't working
$newHtml = $sign + $parentElement.substr(1);
alert($newHtml);
});

我建议您对更新货币的方式进行一些更改,例如

$('.discount-type').on('click', function(event) {
var sign = $(this).html().substr(0, 1);
$(this).closest('ul').prev('.discount-dropdown').find('.currency').text(sign)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle discount-dropdown" data-toggle="dropdown" aria-expanded="false"><span class="currency">$</span> <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right adjustment-dropdown" role="menu">
<li><a class="discount-type">$</a></li>
<li><a class="discount-type">%</a></li>
</ul>
</div>

关于javascript - jQuery .closest() 不选择最近的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339763/

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