2

我只是想在真假之间进行变量切换,并让button点击的文本也改变。这是我的jQuery:

$("button").toggle(
  function () {
    $(this).text("Click to change to paint brush");
      var erasing = true;
  },
  function () {
    $(this).text("Click to change to eraser");
      var erasing = false;
  }
);

这对我来说看起来是 100% 的声音,但在我的jsfiddle中,你会看到它在我点击它之前就切换了按钮的存在!为什么会发生这种情况,我该如何解决?

4

3 回答 3

3

This version of toggle has been deprecated (1.8) and removed (1.9). Now you need to handle it in button click itself. Somthing like this:

var erasing = false;
$("button").click(function () {
    erasing = !erasing;
      $(this).text(function (_, curText) {
          return curText == "Click to change to paint brush" ? "Click to change to eraser" :  "Click to change to paint brush" ;
      });
    console.log(erasing);
  });

Fiddle

Plus if you want to preserve the value of the variable just define them out of the click event scope, so that it is more global to be accessed outside.

See

于 2013-06-23T05:11:42.697 回答
1

谢谢大家解释切换是如何过时的......所以这就是我所需要的,然后我用一个简单的if声明解决了我的问题:

var erasing = false;
var i = 0
$("button").click(function () {
    if(i%2==0){
        $(this).text("Click to change to paint brush");
        erasing = true;
    }
    else{
        $(this).text("Click to change to eraser");
        erasing = false;
    };
    i += 1
  });

jsfiddle

于 2013-06-23T05:21:48.303 回答
0

As PSL said, the toggle you're looking for is gone and lost. if you want a click and hold solution (as your title suggests), you could look at using mouseup and mousedown.

 var erasing;
 $("button").on({
    "mousedown": function () {
        $(this).text("Click to change to paint brush");
        erasing = true;
    },
    "mouseup mouseleave": function () {
        $(this).text("Click to change to eraser");
        erasing = false;
    }
});

Demo : http://jsfiddle.net/hungerpain/ymeYv/6/

于 2013-06-23T05:14:44.373 回答