gpt4 book ai didi

javascript - 仅向列表中的第一个按钮添加功能

转载 作者:行者123 更新时间:2023-11-28 05:48:55 25 4
gpt4 key购买 nike

我的 HTML(精简)

<ul>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
</ul>

我的 JavaScript

$('body').on('click', 'li > button', function() {
$(this).parent().remove();

if($('li > button').length === 1) { // if this is the only button
$(this).parent().parent().remove(); // remove whole list
// remove some other elements outside the list
}

if($(this).parent().is(':first')) { // if this first li in ul
if (confirm("...")) {
$(this).parent().remove();
}
}
});

基本上,我想做的是:

  • 制作第一个按钮以删除父列表项
  • 如果该按钮是 <ul> 中唯一的一个按钮删除整个列表和另一个元素

我怎样才能正确地完成这项工作?

最佳答案

更改您的函数以检查最后一个 <li> 是否已删除(读取: <ul> 不再有 <li> ):

$('body').on( 'click', 'li > button', function() {
var list = $(this).closest( 'ul' );

$(this).parent().remove()

//* if the UL is empty we can remove it altogether
if( list ).find( 'li' ).length == 0 ) remove( list );
});

关于javascript - 仅向列表中的第一个按钮添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38248909/

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