简体   繁体   中英

jquery document ready if statement

I have a bit of jquery that works which you click on a radio button it opens a div. However, on page load the radio button may already be clicked so I would like to have it be open if it is clicked. I would assume I would do the same think below but just change "click" to something else. I cannot figure out exactly what though.

$(".static_class").click(function() {
    if ($(this).val() === "0") {
        $("#none").show("fast");
    } else {
        $("#none").hide("fast");
    }
});

Any ideas?

Checking the radio button's state on page load should work:

$(document).ready(function() {
  if($(".static_class").val()==="0")
    $("#none").show("fast"); 
  else $("#none").hide("fast");
}

Preferably, you should put your if statement in a function, and just call that function on $(document).ready() and on $(".static_class").click()

Also an option is to allow the server-side script to set the div to either display: none if you would not check the radio button or display: block if the radio button button would be checked. This would have the div either show or hide before the page is ready.

Well, there is $(document).ready() :

$(document).ready(function() {
  if ($(this).val() === "0") {
    $("#none").show("fast");
  } else {
    $("#none").hide("fast");
  }
});

Your question is a bit hard to understand. Could you please elaborate a bit more?

Try just adding .click() to the end of your handler assignment to trigger it.

$(".static_class").click(function() {
    if( $(this).val() === "0" ) 
        $("#none").show("fast"); 
    else 
        $("#none").hide("fast");
}).click();

使用jquery触发函数在第二次点击后触发一个事件!

As the "value" attribute in the radio button doesn't change, you should use :checked selector instead:

$(function() {
  if($(".static_class").is(":checked")) {
    ...
  }
}

See: http://api.jquery.com/checked-selector/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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