简单 JQuery show/hide 文本按钮

Simple JQuery show/hide text button

我正在尝试使用 JQuery 进行练习,所以我制作了一个简单的程序...或尝试这样做。有一个按钮,单击该按钮会隐藏页面上唯一的

元素。那很好用。但是,当我再次单击它时,它不会像预期的那样将段落带回来并更改按钮文本。有什么方法可以让我在不使用两个按钮的情况下工作吗?这是脚本现在的样子:

 <script>  
  $(document).ready(function(){

    var t;
    $("button").click(function(){

      if (t === "off") {
         $("p").show();
         $(this).text("hide text");
      }

      $("p").hide();
      $(this).text("show text");
      t = "off";  
    });
 });
</script>
$(document).ready(function(){
var t = "on"; 
$("button").click(function(){

  if (t === "off")
  {
      $("p").show();
      $(this).text("hide text");
      t = "on";
  }
  else
  {
      $("p").hide();
      $(this).text("show text");
      t = "off";  
  }
});

});

类似的东西。基本上 $("p").hide 部分总是触发。

或者更简单,使用toggle函数

那是因为你需要把hide的逻辑放在else中:

if (t === "off") {
    $("p").show();
    $(this).text("hide text");
} else {
    $("p").hide();
    $(this).text("show text");
    t = "off";
}

在你的代码中,当你 "click it again" 时,虽然 toff 并且 $("p") 是在开头显示的,但它会立即变成 hide 再次。

$(document).ready(function(){
var t; 
$("button").click(function(){

  if (t === "off")
  {  
      $(this).text("hide text");
       t = "";  
  } else {      
   $(this).text("show text");
   t = "off";  
   }
$("p").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me!</button>
<p>Paragraph text</p>

已经为您提供了很多答案,所以我只是指出我认为可以做得更好的地方。

  1. 下面的部分代码需要放在else语句中,否则不管t的值是多少,这段代码都会执行。我建议你多了解一下 if-else 条件语句。

     $("p").hide();
     $(this).text("show text");
     t = "off";  
    
  2. $("button").click(function(){你应该使用按钮的id,即$("#nameOfButtonID").click(function(){。了解 html 中的 idclass 属性。 id 是识别哪个按钮处理点击事件的独特方式。
  3. t 可以被视为 boolean

在您的按钮点击功能中,您必须 return 在 if 循环退出之前,您需要设置一些其他值或未定义到 t。

执行顺序: 第一次点击:

  1. t 值为 "undefined"
  2. if 循环不会执行
  3. 隐藏"p"
  4. 将按钮值设置为 'show text' 并将 t 设置为 "off"

第二次点击:

  1. t 值为 "off"
  2. if 循环将执行
  3. 它将显示 'p'
  4. 将按钮值更改为 'hide text'

    ----这里你应该改变t的值和return----

  5. 因为没有return'p'会隐藏

  6. 按钮文本将再次 'show text'。

    $("button").click(function() {
       if (t === "off") {
         $("p").show();
         $(this).text("hide text");
         //add the below code
         t = undefined;
         return;
        }
       $("p").hide();
       $(this).text("show text");
       t = "off";
    });