为了账号安全,请及时绑定邮箱和手机立即绑定

使用jQuery在无限循环中单击按钮时更改按钮的内容

使用jQuery在无限循环中单击按钮时更改按钮的内容

扬帆大鱼 2022-06-09 16:12:44
我想创建一个按钮,在单击时更改其内容,但当我再次单击时,内容必须返回其初始外观。我设法创建了一个 jQuery 代码,它改变了内容,但需要第二次点击的帮助。我的目标是这个按钮有两个条件,当被点击切换到第二个条件时,取决于活动的一个。$("#changeArrow").click(function(){  var textShowing = true;  if (textShowing == true){    $("#changeArrow").html(function(){      return "This is some text! &otimes;";      textShowing = false;    });  }  else {    $("#changeArrow").html(function(){      return "This is some text! &oplus;";      textShowing = true;    });  }});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><button id="changeArrow">This is some text! &oplus;</button>
查看完整描述

2 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

一种方法是提供一个函数来html()检查当前内容是什么,并根据它返回新内容,如下所示:


$("#changeArrow").click(function() {

  $(this).html((i, h) => h == 'This is some text! ⊕' ? 'This is some text! ×' : 'This is some text! ⊕');

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text! &oplus;</button>

但是,由于您所做的只是更改图标,因此如果您使用 CSS 添加图标,这可能会变得更加简单。然后你可以简单地在每次点击时切换一个类:


$("#changeArrow").click(function() {

  $(this).toggleClass('close');

});

#changeArrow:after {

  content: '⊕';

  margin: 0 -1px 0 4px;  

  display: inline-block;

}

#changeArrow.close:after {

  content: '×';

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text!</button>


查看完整回答
反对 回复 2022-06-09
?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您应该在 click 事件处理函数之外声明标志变量 ( textShowing )。此外,您可以使用this关键字来引用单击的元素:


var textShowing = true;

$("#changeArrow").click(function(){

  if (textShowing == true){

    $(this).html("This is some text! &otimes;");

    textShowing = false;


  } else {

    $(this).html("This is some text! &oplus;");

    textShowing = true;

  }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="changeArrow">This is some text! &oplus;</button>


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 285 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号