1

我试图在页面打开时隐藏一个元素,然后在单击按钮时显示,但它不显示该元素。我希望隐藏 ID 为 extraForm 的表单,直到按下按钮

<!DOCTYPE html>
<head>

<script src="Javascripts/jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#extraForm").hide()
});
$('#showForm').click(function(){
$('#extraForm').show();
});
</script>
<link rel='stylesheet' href='website.css'>
</head>
<body>
<form action="submit.php" method="post">
<table> <table border="1"> <tr>
<tr> <td> First Name:     </td> <td> <input type="text" name="firstName">  </td> </tr> 
<tr> <td> Last Name:      </td> <td> <input type="text" name="lastName">   </td> </tr>
<tr> <td> Dorm Name:      </td> <td> <input type="text" name="dormName">   </td> </tr>
<tr> <td> Room Number:    </td> <td> <input type="text" name="roomNumber"> </td> </tr>

<tr> <td> Pizza Type:     </td> <td> <input type="radio" name="pizzaType" value="Cheese">       
Cheese
<input type="radio" name="pizzaType" value="Pepperoni"> Pepperoni <br>
<input type="radio" name="pizzaType" value="Buffalo Chicken"> Buffalo Chicken </td>
<tr> <td> Number of Pizza's:  <td>   <input type="text" name="pizzaNumber"> </td> </tr>
<tr> <td> </td> <td>  <input type="submit"> </tr> </td>

<table> <table border="1" id="extraForm">
<tr> <td> <input type="radio" name="pizzaType" value="Cheese"> Cheese</td> </tr>
<tr> <td> <input type="radio" name="pizzaType" value="Buffalo Chicken"> Buffalo Chicken      
</td> </tr>
<tr> <td> <input type="radio" name="pizzaType" value="Pepperoni"> Pepperoni</td> </tr>
<input type="button" name="showForm" value="Add Pizza" id="showForm">
</table>


</table>

</form>

</body>
</html>
4

4 回答 4

6

It is always better to use CSS to hide elements that you don't need on page load

#extraForm { display: none }​

Your script doesn't work because you try to attach the event listener to an element that doesn't yet exist when the script runs. To fix it your jQuery needs to wait for the DOM to be ready:

$(function() {
    $('#showForm').click(function() {
        $('#extraForm').show();
    });
});

DEMO

于 2012-11-30T01:25:12.573 回答
3

Since you need the form to be hidden when the page loads you could use CSS to hide it.

<table border="1" id="extraForm" style="display:none">

When you need the form to be displayed, simply use
$('#extraForm').show();

Here is a working demo

Dont forget to include the jquery library in your code.

于 2012-11-30T01:26:49.903 回答
1

将脚本放在 HTML 文档的末尾或将其包装在:

$(document).ready(function(){
  // place code here
});
于 2012-11-30T01:22:31.753 回答
0

尝试这个:

<script type="text/javascript">
    $(document).ready(function () {
        $("#extraForm").hide()
        $('#showForm').click(function(){
            $('#extraForm').show();
        });
    });
</script>

$("#extraForm").hide()不需要在函数中 - 它在页面加载时运行。

于 2012-11-30T01:22:50.557 回答