最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery document ready if statement - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jun 8, 2013 at 19:41 Joe 15.6k8 gold badges50 silver badges57 bronze badges asked Jan 24, 2011 at 3:08 keithkeith 111 gold badge1 silver badge2 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 1

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();

Use jquery trigger function trigger an event after second click that will do it!

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./checked-selector/

发布评论

评论列表(0)

  1. 暂无评论