jquery将div元素可见性视为真,即使不可见

时间:2015-03-18 04:04:56

标签: javascript jquery

我有一个简单的表单,我有jquery代码,用于确定id =“placeholder”的div元素是否可见。如果可见,则显示带有错误消息的警告框,如果没有,则显示带有确认消息的警告框。问题是当我单击提交按钮时,它会在警告框中显示错误消息,而不是OK警报消息。令人费解的是,即使div元素没有innerHTML文本,它仍会显示错误更改框。代码有什么问题?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<form>
  <fieldset>
    <legend>Your Information:</legend>
    First name:
    <br>
    <input type="text" name="firstname">
    <br>Last name:
    <br>
    <input type="text" name="lastname">
    <br>
    <br>
    <input type="button" value="Submit" onclick="dopost()">
  </fieldset>
</form>

<div id="placeholder"></div>

<script>
  function dopost() {

    if ($('#placeholder').is(':visible')) {

      alert('Found errors in the form, please correct them!');

    } else {

      alert('no errors');

    }

  }
</script>

1 个答案:

答案 0 :(得分:2)

试试这个。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<form>
  <fieldset>
    <legend>Your Information:</legend>
    First name:
    <br>
    <input type="text" name="firstname">
    <br>Last name:
    <br>
    <input type="text" name="lastname">
    <br>
    <br>
    <input type="button" value="Submit" onclick="dopost()">
  </fieldset>
</form>

<div id="placeholder" style="visibility:hidden;"></div>

<script>
  function dopost() {
     
    if ($('#placeholder').attr('visibility')=='visible') {

      alert('Found errors in the form, please correct them!');

    } else {

      alert('no errors');

    }

  }
</script>
&#13;
&#13;
&#13;