我有一个脚本放在我的 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;
});
});
最佳答案
您很可能在脚本引用的元素存在之前运行该脚本。
确保 <script>
标签在页面中出现的时间晚于类 table
的元素。或将整个脚本包装在:
$(function(){
... Your entire script
});
为了确保在 DOM 准备好之前它不会执行。
关于javascript - 我的脚本只能从控制台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781758/