简体   繁体   English

jQuery显示/隐藏字段第一次无法正常工作

[英]JQuery show/hide field not working properly the first time

I am having some trouble with this snippet of code. 我在这段代码中遇到了一些麻烦。 It works, but only after I click on the radio button it is being affected by twice. 它有效,但只有在单击单选按钮后,它才会受到两次影响。 When I click the button the first time, it does not work, but if I give it a second click, it will. 当我第一次单击该按钮时,它不起作用,但是如果我再次单击它,它将起作用。 Am I doing something wrong? 难道我做错了什么? Is there a better way of doing this? 有更好的方法吗?

function hide(){
   $(document).ready(function(){
      $("input[id$='yes']").click(function(){
         $("div#hidden").fadeOut(2000);
      });
   });
};

This is what I have in my header. 这就是我的标题中的内容。 I have another just like only it's called show() which is affected by another radio button. 我有另一个,就像它叫做show()一样,它受另一个单选按钮的影响。 When you click on one it hides a div, when you click on the other it shows it. 当您单击一个时,它会隐藏一个div,当您单击另一个时,它会显示它。

Here is the radio button which affects the script to whether the div is hidden or shown. 这是单选按钮,可影响脚本是否隐藏或显示div。

<input type="radio" name="field1" id="yes" value="Y" onClick="hide();" />Yes

Again, there is another just like it only it is no. 再说一次,有另一个就是它没有。 Now, the div being hidden is: 现在,隐藏的div是:

<div id="hidden"><input type="text" name="extrafield1" id="no_box" size="20" maxlength="20" /></div>

Again, when the No radio button is clicked it should appear, when the Yes radio button is clicked it should hide. 同样,当单击“否”单选按钮时,它应该出现,当单击“是”单选按钮时,它应该隐藏。 It works, but you must click on the radio button twice. 它可以工作,但是您必须单击两次单选按钮。

This snippet hides the div when the page loads: 该代码段在页面加载时隐藏div:

function loadHidden(){
    $("div#hidden").hide();
}

<body onLoad="loadHidden()">

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

You have your document.ready event defined within the hide function, so the event for the click function isn't registered when the document first loads. 您在hide函数中定义了document.ready事件,因此在第一次加载文档时不会为click函数事件注册。 Try a structure like this: 尝试这样的结构:

$(document).ready(function(){
    $("input[id$='yes']").click(function(){
        $("div#hidden").fadeOut(2000);
    });

    $("input[id$='no']").click(function(){
        $("div#hidden").fadeIn(2000);
    });
});

This way, the click event is all set up when the document is ready, and you won't need the onClick attributes on your radio buttons. 这样,单击事件将在文档准备就绪时全部设置,并且您将不需要单选按钮上的onClick属性。

Looks like hide() was causing a problem. 看起来hide()引起了问题。 Try this fiddle . 试试这个小提琴

Just write your logic in document.ready in element click events it should work. 只需将您的逻辑写入document.ready在元素单击事件中就可以了。

Try this: 尝试这个:

$(document).ready(function(){
  $(':radio[name=field1]').change(function () {
     if($(this).val()=='Y'){
       $("div#hidden").fadeOut(2000);
     }
     else{
       $("div#hidden").fadeIn(2000);
     }
  });
});

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

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