当用户点击span
到hierchical树ul
HTML元素时,我正在尝试添加按钮。
这是一个例子:
<ul class="tree">
<li>
<span class="li_cat">Food</span>
<ul class="tree">
<li>
<span class="li_cat">Fruit</span>
<ul class="tree">
<li>
<span class="li_cat">Red</span>
<ul class="tree">
<li><span class="li_cat">Cherry</span></li>
</ul>
</li>
<li>
<span class="li_cat">Yellow</span>
<ul class="tree">
<li><span class="li_cat">Banana</span></li>
</ul>
</li>
</ul>
</li>
<li>
<span class="li_cat">Meat</span>
<ul class="tree">
<li><span class="li_cat">Beef</span></li>
<li><span class="li_cat">Pork</span></li>
</ul>
</li>
</ul>
</li>
</ul>
jquery代码是这样的:
$(document).on('click', '.li_cat', function(e){
e.stopPropagation();
$(this).html($(this).html()+" <button class='btn btn-warning btn-xs'><i class='glyphicon glyphicon-pencil'></i></button>");
});
我想要显示一次按钮,但每次点击添加新按钮时,我该如何解决这个问题?
答案 0 :(得分:1)
在namespace
附加click
事件时设置document
,以引用特定于click
元素的.li_cat
事件。检查元素.attr("data-keyname")
,如果元素没有.attr("data-keyname")
,则在元素Boolean
设置.attr("data-keyname")
标记,使用.html(function)
。如果所有click
个元素都document
设置为.li_cat
,请移除.attr("data-keyname")
处的委派true
个活动。
$(document).on('click.cat', '.li_cat', function(e) {
e.stopPropagation();
if ($(this).attr("data-clicked") === undefined) {
$(this).attr("data-clicked", true).html(function(_, html) {
return html + "<button class='btn btn-warning btn-xs'><i class='glyphicon glyphicon-pencil'>button</i></button>"
});
// if all `.li_cat` elements have `data-clicked` attribute
if ($(".li_cat[data-clicked]").length === $(".li_cat").length) {
// remove `click` event listener for `.li_cat` elements
$(document).off("click.cat")
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tree">
<li>
<span class="li_cat">Food</span>
<ul class="tree">
<li>
<span class="li_cat">Fruit</span>
<ul class="tree">
<li>
<span class="li_cat">Red</span>
<ul class="tree">
<li><span class="li_cat">Cherry</span>
</li>
</ul>
</li>
<li>
<span class="li_cat">Yellow</span>
<ul class="tree">
<li><span class="li_cat">Banana</span>
</li>
</ul>
</li>
</ul>
</li>
<li>
<span class="li_cat">Meat</span>
<ul class="tree">
<li><span class="li_cat">Beef</span>
</li>
<li><span class="li_cat">Pork</span>
</li>
</ul>
</li>
</ul>
</li>
</ul>
答案 1 :(得分:1)
首先empty
span
,然后根据需要button
添加button
一次。此外,这还将确保先前添加的button
与events
一起删除。
$(document).on('click', '.li_cat', function(e){
e.stopPropagation();
var spanText = $(this).text();
$(this).empty();
$(this).append(spanText);
$(this).append("<button class='btn btn-warning btn-xs'><i class='glyphicon glyphicon-pencil'></i></button>");
});