Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - Does something like jQuery.toggle(boolean) exist?

I write something similar to the following code a lot. It basically toggles an element based on some condition.

In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".

$("button").click(function() {
  if ($("#agree").is(":checked") && $("#name").val() != "" ) {
    $("#mydiv").show();
  } else {
    $("#mydiv").hide();
  }
});

I wish there was some sort of jQuery function that would work like this.

$("button").click(function() {
  var condition = $("#agree").is(":checked") && $("#name").val() != "" );
  $("#mydiv").toggle(condition);
});

Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, so I am an idiot and need to RTM before I ask questions.

jQuery.toggle() allows you to do this out of the box.

$("button").click(function() {
  var condition = $("#agree").is(":checked") && $("#name").val() != "" );
  $("#mydiv").toggle(condition);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...