如何使用JQUERY来调用随机表单

Dja*_*way 2 html jquery

我想知道是否有人可以提供一些见解,为什么当我点击下面的随机表格链接时,它不会随机加载其中一个列出的表格.它适用于jfiddle:

http://jsfiddle.net/tUMBp/1/

任何帮助将不胜感激.提前致谢.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script src="http://code.jquery.com/jquery-1.7.2.js" type="text/javascript"></script><!-- This calls the jquery library -->

<script type="text/javascript">
$(document).ready(function() {
    $('#randomForm').click(function() {
        var forms = $('#forms > form');
        forms.hide();
        forms.eq(Math.floor(Math.random() * forms.length)).show();
    });
});
</script>

<title>Untitled Document</title>
</head>

<body>

<div id="forms">
    <form style="display:none;">
        This is your training site1
    </form>
    <form style="display:none;"><!-- the second form -->
        This is your training site2
    </form>
    <form style="display:none;"><!-- the second form -->
        This is your training site3
    </form>

    <form style="display:none;"><!-- the second form -->
       This is your training site4
    </form>


</div>



<a href="#" id="randomForm">Show random form</a>?



</body>
</html>
Run Code Online (Sandbox Code Playgroud)

bfa*_*tto 5

问题是您的jquery代码在页面上存在任何表单之前运行.此时,您无法将click事件分配给#randomForm(jQuery将尝试,但由于#randomForm尚不存在,它将不执行任何操作).

使用document.ready处理程序:

<script type="text/javascript">
$(document).ready(function(){
    $('#randomForm').click(function() {
        var forms = $('#forms > form');
        forms.hide();
        forms.eq(Math.floor(Math.random() * forms.length)).show();
    });?
});?
</script>
Run Code Online (Sandbox Code Playgroud)