仅向列表中的第一个按钮添加功能
Add functionality to first button in list only
My 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 );
});
你只需要评估是否有多个元素,试试这个:
$('body').on('click', 'li > button', function() {
if(($('li > button').length > 1)) {
$(this).parent().remove();
} else {
$(this).parents('ul').remove();
console.log('Remove other items')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
<li>
<p></p>
<p></p>
<button type="button">Remove</button>
</li>
</ul>
相关文章:
- 将按钮添加到新元素中
- 使用加号按钮添加多个文本框,并通过PHP提交
- 复选框/单选按钮-添加所选项目的总价
- 将自定义按钮添加到现有网站
- 单击按钮添加HTML表单
- 将sharethis按钮添加到chrome扩展popup.html
- 从自定义DocuSign按钮添加信封自定义字段
- 我尝试将引导下拉按钮添加到 但下拉菜单不起作用.我该怎么做
- 将按钮添加到跨度
- 使用按钮添加到变量
- 单击禁用的按钮添加 CSS
- 将“下一步”和“上一个”按钮添加到较大的图像
- 将下一个和上一个按钮添加到我的图像滑块
- 按React按钮添加行
- 用jQuery点击按钮添加值
- 如何将下一个和上一个按钮添加到图像galary
- 如何为表行结果的每个按钮添加事件侦听器
- 使用setTimeout为按钮添加冷却时间
- 无法向按钮添加属性
- 如何将我的附加按钮添加到这个jQuery mp3播放器中