我试图在我的 document.ready 事件中创建一个循环,以便我可以有干代码。但是,当我通过循环创建它时,单击事件返回未定义,但是当我单独声明每个 document.ready 事件时,它工作正常。
<script>
var $a = jQuery.noConflict();
$a(document).ready(function () {
$a(".nav-1-1").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-1").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-2").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-2").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-3").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-3").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-4").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-4").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-5").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-5").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-6").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-6").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-7").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-7").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-8").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-8").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-9").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-9").find("a").attr("href");
});
});
$a(document).ready(function () {
$a(".nav-1-10").css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-10").find("a").attr("href");
});
});
</script>
这是我试图简化上述代码的循环:
<script>
var $a = jQuery.noConflict();
$a(document).ready(function () {
for (var i=1; i<11; i++) {
$a(".nav-1-1"+i).css('cursor','pointer').click(function(event) {
window.location.href = $a(".nav-1-1").find("a").attr("href");
});
}
});
</script>
正如 Trevor 指出的那样,我已经更正了上述循环,因为我忘记了包含 i 变量。