简体   繁体   English

如何在点击事件上切换两个单词

[英]How to toggle two words on click event

I want to toggle open and hide words when I toggle the panel. 当我切换面板时,我想切换打开并隐藏单词。

Here is the code I used. 这是我使用的代码。 it works only for hide but when I click next time it doesnt show open. 它仅适用于隐藏,但是当我下次点击时它不显示打开。

$(document).ready(function(){
        $(".flip1").click(function(){
            $(".panel1").slideToggle("slow");
       var val= 0;
       if(val==0){
        $('#word').html("hide").show();
        val=1;
       }else{
        $('#word').html("open").show();
        val=0;

       }
           // $(".info").hide();
        });
    });

help me to correct this. 帮我纠正这个。

Move this line: 移动这一行:

var val= 0;

Out of the click() callback. click()回调之外。

Where you have it it is a local variable within your click handler, and it gets set to 0 every time the handler is called. 你拥有它的地方是你的点击处理程序中的局部变量,每次调用处理程序时它都会被设置为0 Move it outside the handler and it will get initialised to 0 once, and then updated within the click handler. 将它移到处理程序之外,它将初始化为0 ,然后在单击处理程序中更新。

Alternatively, get rid of that variable altogether and do something like this: 或者,完全摆脱该变量并执行以下操作:

$(document).ready(function(){
    $(".flip1").click(function(){
        $(".panel1").slideToggle("slow");
        $("#word").html(function(i,oldHtml) {
           return oldHtml==="hide"?"show":"hide";
        }).show();
    });
});

Demo: http://jsfiddle.net/9S5eq/ 演示: http//jsfiddle.net/9S5eq/

EDIT: If you pass a callback to the .html() method , jQuery calls it for each element in the jQuery object, passing the index of the current element within the object and that element's current html. 编辑:如果您将回调传递给.html()方法 ,jQuery会为jQuery对象中的每个元素调用它,传递对象中当前元素的索引以及该元素的当前html。 It sets the html to whatever value you return. 它将html设置为您返回的任何值。 So in this case where there is only one element the index parameter isn't actually needed at all, but you can't leave it out because the current value is passed in the second parameter (so i is just a sort of placeholder). 因此,在这种情况下,只有一个元素根本不需要索引参数,但是你不能将它遗漏掉,因为当前值是在第二个参数中传递的(所以i只是一种占位符)。

you can use this code 你可以使用这段代码

 $(document).ready(function(){
    var val= 0;
    $(".flip1").click(function(){
        $(".panel1").slideToggle("slow");

   if(val==0){
    $('#Word').html("hide").show();
    val=1;
   }else{
    $('#Word').html("open").show();
    val=0;

   }
       // $(".info").hide();
    });
});

you must use var val=0 before the click event of the .flip1 你必须在.flip1的click事件之前使用var val=0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM