2013-05-27 26 views
0

我有一个脚本放在我的html文档中。我的脚本只能从控制台工作

当我加载HTML页面脚本不工作,但是当我把脚本放在控制台内,然后脚本正在工作,使我想要的HTML文件的效果。

这里是脚本,我做错了什么?

var maxRows = 10; 
$('.table').each(function() { 
var cTable = $(this); 
var cRows = cTable.find('tr:gt(0)'); 
var cRowCount = cRows.size(); 

if (cRowCount < maxRows) { 
    return; 
} 

cRows.each(function(i) { 
    $(this).find('td:first').text(function(j, val) { 
     return (i + 1) + " - " + val; 
    }); 
}); 

cRows.filter(':gt(' + (maxRows - 1) + ')').hide(); 


var cPrev = cTable.siblings('.prev'); 
var cNext = cTable.siblings('.next'); 

cPrev.addClass('disabled'); 

cPrev.click(function() { 
    var cFirstVisible = cRows.index(cRows.filter(':visible')); 

    if (cPrev.hasClass('disabled')) { 
     return false; 
    } 

    cRows.hide(); 
    if (cFirstVisible - maxRows - 1 > 0) { 
     cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show(); 
    } else { 
     cRows.filter(':lt(' + cFirstVisible + ')').show(); 
    } 

    if (cFirstVisible - maxRows <= 0) { 
     cPrev.addClass('disabled'); 
    } 

    cNext.removeClass('disabled'); 

    return false; 
}); 

cNext.click(function() { 
    var cFirstVisible = cRows.index(cRows.filter(':visible')); 

    if (cNext.hasClass('disabled')) { 
     return false; 
    } 

    cRows.hide(); 
    cRows.filter(':lt(' + (cFirstVisible +2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show(); 

    if (cFirstVisible + 2 * maxRows >= cRows.size()) { 
     cNext.addClass('disabled'); 
    } 

    cPrev.removeClass('disabled'); 

    return false; 
}); 

});

+0

你的代码你收到任何错误讯息? – basilikum

回答

1

你很可能在它引用的元素存在之前运行该脚本。

确保<script>标签后进来的页面不是与类table或包裹整个脚本元素:

$(function(){ 

... Your entire script 

}); 

,以确保它不会执行,直到DOM就绪。

+0

谢谢你现在在工作 –

+0

@LiranTadmor不客气:) – Paulpro

+0

我在哪里把函数名放在你给我展示的例子中? –

2

尝试包裹整个事情与此:

$(document).ready(function() { /* existing code */ }); 

该浏览器可以执行代码之前在页面加载,因此之前的元素存在。

0

在文档“准备就绪”之前,不能安全地操作页面。 jQuery为你检测到这种状态。包含在 $(document).ready()中的代码只会在页面Document Object 模型(DOM)准备好执行JavaScript代码时运行。在$(window).load(function(){...})内部包含代码 将在整个页面(图像或iframe)(而不仅仅是DOM)准备就绪后运行。

尝试包裹在这

$(document).ready(function() { 
    // Your code here 
}); 

The Source

相关问题