jquery代码不会更改div的可见性属性

时间:2015-03-18 23:52:50

标签: javascript jquery html css

我有一个简单的字段表格来证明这一点。我有一个隐藏的div,它可以作为错误信息。如果firstname输入字段为空,那么我想将div的可见性更改为visible,但我的jquery代码没有这样做,并且jquery语句下面的任何代码都不会执行。因此,警报框永远不会弹出。我正在改变div的可见性:$("#name_require").css("visibility", "visible");

HTML code:

<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Roboto:400,700">

<script>
  function validateForm() {


    var firstname = document.forms["myform"]["firstname"].value;

    var errors = false;

    if (firstname == "") {

      errors = true;

      $("#name_require").css("visibility", "visible"); //This fails all the javascript below it does not execute and the alter box never pops up.

      alert('name field is empty');

    }


  }
</script>

<body>


  <div class="ss-form-container">
    <div class="ss-header-image-container">
      <div class="ss-header-image-image">
        <div class="ss-header-image-sizer"></div>
      </div>
    </div>
    
    <div class="ss-form">
      <form id="ss-form" name="myform">
        <ol role="list" class="ss-question-list" style="padding-left: 0">
          <div class="ss-form-question errorbox-good" role="listitem">
            <div dir="ltr" class="ss-item ss-item-required ss-text">
              <div class="ss-form-entry">
                <label class="ss-q-item-label" for="entry_710276695">
                  <div class="ss-q-title">First name

                    <span class="ss-required-asterisk" aria-hidden="true">*</span>
                  </div>
                  <div class="ss-q-help ss-secondary-text" dir="ltr"></div>
                </label>
                <input type="text" name="firstname" value="" class="ss-q-short" id="entry_710276695" dir="auto">
                
                <div id="name_require" style="visibility:hidden;color:red;">This is a required question</div>
              </div>
            </div>
          </div>
          
          <div class="ss-item ss-navigate">
            <input type="button" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action " onclick="validateForm()">

          </div>
        </ol>
      </form>
    </div>
  </div>

  <br>

</body>

2 个答案:

答案 0 :(得分:0)

如何将DOM中的style="visibility:hidden;color:red;"替换为style="display:none;color:red;",将脚本中的$("#name_require").css("visibility", "visible");替换为$("#name_require").toggle();

答案 1 :(得分:0)

解决方案:在HTML文件中包含指向Jquery库文件的链接。