[英]When appending a font awesome icon in a button using jQuery the icon disappears when I click another button
I am making a to do list web app using jQuery. 我正在使用jQuery创建待办事项列表Web应用程序。 I have a grey bootstrap button with an empty box icon (from font awesome) to show an item is incomplete.
我有一个灰色的自举按钮,带有一个空框图标(从真棒字体显示),表示项目不完整。 When the user completes the task I want the button to become green and the icon to change into a checked box icon (from font awesome also).
当用户完成任务时,我希望按钮变为绿色,并且图标更改为复选框图标(字体也很棒)。 I can get the button to become green by changing the class and the icon to change for one item however when I click another item to mark as complete the previous button stays green however the checked box icon disappears.
我可以通过更改类来使按钮变为绿色,并更改一个项目的图标,但是当我单击另一项目以标记为完成时,上一个按钮保持绿色,但是复选框图标消失了。
Essentially the code for the icon which is <i class="fa fa-check-square-o"></i>
gets removed from the code of the first button that is clicked once the second button is clicked however the previous button still stays green. 本质上,图标的代码
<i class="fa fa-check-square-o"></i>
从单击第二个按钮后单击的第一个按钮的代码中删除,但是上一个按钮仍然保持绿色。 The same thing happens to the second button when I click a third button. 当我单击第三个按钮时,第二个按钮也会发生同样的事情。 How can I get
<i class="fa fa-check-square-o"></i>
to stay? 如何获得
<i class="fa fa-check-square-o"></i>
留下来? Thanks in advance for any help. 在此先感谢您的帮助。
var checked = $("<i>").addClass("fa fa-check-square-o");
$("table").on("click", ".btn-default", function(){
$(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
});
simply put the checked element into click scope 只需将选中的元素放入点击范围
$(document).on("click", ".btn-default", function(){
checked = $("<i>").addClass("fa fa-check-square-o");
$(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
});
otherwise it will always reference the same <i>
element and append it to the next clicked button 否则,它将始终引用相同的
<i>
元素并将其附加到下一个单击的按钮上
尝试简化这条线
$(this).replaceWith("<button type='button' class='btn btn-success'><li class='fa fa-check-square-o'></li></button");
Move the declaration of var checked into the click handler. 将已检查的var声明移动到单击处理程序中。 The reason is that you're creating a single element and moving it around each time you call .append.
原因是您要创建一个元素,并在每次调用.append时将其移动。
From the .append docs 来自.append文档
http://api.jquery.com/append/ http://api.jquery.com/append/
"If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)" “如果将以此方式选择的元素插入到DOM中其他位置的单个位置,则它将被移动到目标中(未克隆)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.