Javascript 在JQuery中,如何仅通过单击按钮而不是整个元素来删除li元素?
在JQuery中,如何仅通过单击按钮而不是整个元素来删除li元素Javascript 在JQuery中,如何仅通过单击按钮而不是整个元素来删除li元素?,javascript,jquery,html,twitter-bootstrap,Javascript,Jquery,Html,Twitter Bootstrap,在JQuery中,如何仅通过单击按钮而不是整个元素来删除li元素 让addGroupBtn=$(“.addGroupBtn”); 让createGroupList=$(“.createGroupList”); 让createGroupsContainer=$(“.createGroups容器”); 让createGroupName=$(“.createGroupName”); 让removeGroupItemBtn=$(“.remove group item btn”); addGroupBt
让addGroupBtn=$(“.addGroupBtn”);
让createGroupList=$(“.createGroupList”);
让createGroupsContainer=$(“.createGroups容器”);
让createGroupName=$(“.createGroupName”);
让removeGroupItemBtn=$(“.remove group item btn”);
addGroupBtn.单击((e)=>{
e、 预防默认值();
让createGroupNameValue=createGroupName.val()
如果($.trim(createGroupNameValue)!=“”){
createGroupList.append(`
去除
`);
createGroupName.val(“”);
};
});代码>
添加组
问题是因为您提供了一个jQuery对象作为on()
事件处理程序的委托目标。这应该是一个字符串选择器。试试这个:
$(createGroupsContainer).on('click', ".remove-group-item-btn", (e) => {
$(e.target).closest('li').remove();
});
还请注意,在一些地方,您正在双重包装jQuery对象,这应该避免。下面是一个正确的工作示例:
让$addGroupBtn=$(“.addGroupBtn”);
让$createGroupList=$(“.create group list”);
让$createGroupsContainer=$(“.createGroups容器”);
让$createGroupName=$(“.create group name”);
让$removeGroupItemBtn=$(“.remove group item btn”);
$addGroupBtn.单击((e)=>{
e、 预防默认值();
让createGroupNameValue=$createGroupName.val()
如果($.trim(createGroupNameValue)!=“”){
$createGroupList.append(`
去除
`);
$createGroupName.val(“”);
};
});
$createGroupsContainer.on('单击',''。删除组项btn',(e)=>{
$(e.target).最近('li').remove();
});代码>
添加组
当您单击标签内的按钮时,我们需要删除整个标签。
请找到以下解决方案
HTML是:
<ul>
<li>
<section>
<div class="">
<p>Sample text here and some more here 1</p>
<button class="remove">Remove</button>
</div>
</section>
</li>
<li>
<section>
<div class="">
<p>Sample text here and some more here 2</p>
<button class="remove">Remove</button>
</div>
</section>
</li>
<li>
<section>
<div class="">
<p>Sample text here and some more here 3</p>
<button class="remove">Remove</button>
</div>
</section>
</li>
<li>
<section>
<div class="">
<p>Sample text here and some more here 4</p>
<button class="remove">Remove</button>
</div>
</section>
</li>
</ul>
我还为此制作了一把小提琴:就是这样,谢谢。谢谢@罗里姆克罗桑指出了我遗漏的东西,这似乎奏效了。基本上使用JQuery对象而不是字符串。
// handle click and add remove Li
$(".remove").on("click", function(){
$(this).parents("li").remove();
})