Javascript 无法在单击事件时更新按钮文本和字体图标

Javascript 无法在单击事件时更新按钮文本和字体图标,javascript,jquery,Javascript,Jquery,如何正确更改/更新单击事件按钮的文本和字体图标 $(“.btn警告”)。单击(函数(){ $(this).toggle(函数(){ $('.btn warning').text(“删除过滤器”); },函数(){ $('.btn warning')。文本(“应用过滤器”); }); }); 应用过滤器试试这个。我想这或多或少会让你开始 应用过滤器 $(“.btn警告”)。单击(函数(){ $(this.html('这是一个新名称bro'); $(this.find($(“.fa”)).r

如何正确更改/更新单击事件按钮的文本和字体图标

$(“.btn警告”)。单击(函数(){
$(this).toggle(函数(){
$('.btn warning').text(“删除过滤器”);
},函数(){
$('.btn warning')。文本(“应用过滤器”);
});
});


应用过滤器
试试这个。我想这或多或少会让你开始


应用过滤器
$(“.btn警告”)。单击(函数(){
$(this.html('这是一个新名称bro');
$(this.find($(“.fa”)).removeClass('fa-filter').addClass('fa-remove');
});
给你

$(“.btn警告”)。单击(函数(){
var$btn=$(本);
如果($btn.hasClass('x-on')){
$btn.removeClass('x-on').html(“应用过滤器”);
}否则{
$btn.addClass('x-on').html(“删除过滤器”);
}
});


应用过滤器
切换
无法按此代码所希望的方式工作。这并不意味着
执行此操作
执行其他操作
——当您
切换
时,会导致JQuery淡出/在元素中,并在动画完成时执行函数调用

因此,您单击
并淡出元素,但是现在没有任何东西可以单击
将其恢复,您的更改将不会被看到

要在单击时更改代码,我们只需在函数本身上设置一个变量(
this.clicked
),并根据是第一次还是第二次单击来切换元素的
html
。这将通过检查This.checked是否为真来确定

$(".btn-warning").click(function() {
  if (this.clicked == undefined) this.clicked = false;
  this.clicked = !this.clicked;

  (this.clicked) ?
  $('.btn-warning').html("Remove Filter <i class='fa fa-filter'></i>") :
  $('.btn-warning').html("Apply Filter <i class='fa fa-remove'></i>");
});
$(“.btn警告”)。单击(函数(){
如果(this.clicked==未定义)this.clicked=false;
this.clicked=!this.clicked;
(点击这个按钮)?
$('.btn warning').html(“删除筛选器”):
$('.btn warning').html(“应用过滤器”);
});
$(“.btn警告”)。单击(函数(){
设btn=$(“.btn警告”);
如果(this.clicked==未定义)this.clicked=false;
this.clicked=!this.clicked;
(点击这个按钮)?
html(“删除过滤器”):
html(“应用过滤器”);
});

应用过滤器(1)JQuery方法将切换按钮可见性,您不需要这个

(2)如果需要更改元素的html,请不要使用该方法,而是使用该方法。
text()
方法将无法识别所需的
html
标记

您可以使用的一种方法是检测按钮内的
标记是否具有某种类别(请阅读),然后根据以下情况采取行动:

$(“.btn警告”)。单击(函数()
{
if($(this.find(“i”).hasClass(“fa过滤器”))
$(this.html(“删除过滤器”);
其他的
$(this.html(“应用过滤器”);
});

应用过滤器
$(".btn-warning").click(function() {
  if (this.clicked == undefined) this.clicked = false;
  this.clicked = !this.clicked;

  (this.clicked) ?
  $('.btn-warning').html("Remove Filter <i class='fa fa-filter'></i>") :
  $('.btn-warning').html("Apply Filter <i class='fa fa-remove'></i>");
});