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

我想创建一个按钮,在单击时更改其内容,但当我再次单击时,内容必须返回其初始外观。我设法创建了一个 jQuery 代码,它改变了内容,但需要第二次点击的帮助。我的目标是这个按钮有两个条件,当被点击切换到第二个条件时,取决于活动的一个。


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

  var textShowing = true;

  if (textShowing == true){

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

      return "This is some text! ⊗";

      textShowing = false;

    });

  }

  else {

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

      return "This is some text! ⊕";

      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>


扬帆大鱼
浏览 286回答 2
2回答

函数式编程

一种方法是提供一个函数来html()检查当前内容是什么,并根据它返回新内容,如下所示:$("#changeArrow").click(function() {&nbsp; $(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() {&nbsp; $(this).toggleClass('close');});#changeArrow:after {&nbsp; content: '⊕';&nbsp; margin: 0 -1px 0 4px;&nbsp;&nbsp;&nbsp; display: inline-block;}#changeArrow.close:after {&nbsp; 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>

慕侠2389804

您应该在 click 事件处理函数之外声明标志变量 ( textShowing )。此外,您可以使用this关键字来引用单击的元素:var textShowing = true;$("#changeArrow").click(function(){&nbsp; if (textShowing == true){&nbsp; &nbsp; $(this).html("This is some text! &otimes;");&nbsp; &nbsp; textShowing = false;&nbsp; } else {&nbsp; &nbsp; $(this).html("This is some text! &oplus;");&nbsp; &nbsp; textShowing = true;&nbsp; }});<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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript