我有一个包含两个函数的 js 文件,一个使用纯 JavaScript,另一个使用 jQuery。我希望两者都能在窗口加载时工作。但如果我同时启用两者,则只有纯 JavaScript 函数可以工作。当我禁用“highliter”功能时,“slideSwitch”工作正常。问题是什么?我该如何解决这个问题?
function slideSwitch() {
var active = $('#slideshow img.active'),
next;
if (active.length == 0){
active = $('#slideshow img:last');
};
next = active.next().length ? active.next() : $('#slideshow img:first');
active.addClass('last-active');
next.addClass('active')
.css({opacity:0.0})
.animate({opacity:1.0}, 1000, function() {
active.removeClass('active last-active');
});
};
function startSlideShow() {
setInterval("slideSwitch()", 5000);
};
function highliter() {
var current = document.location.pathname;
var nav = document.getElementById('pages');
var a_tags = nav.getElementsByTagName('a');
for (var i = 0; i <= a_tags.length; i++) {
if (a_tags[i].getAttribute('href') === current) {
a_tags[i].parentElement.className = 'highlited';
}
}
};
window.onload = function() {
highliter();
startSlideShow();
};
最佳答案
highliter() 中是否发生了 javascript 错误?我发现两个可能的问题:
- 您的 for 循环正在检查 <= length 而不是 < length,这意味着您超出了数组的大小。
- 我可以看到页面上没有 id 为“pages”的元素,这意味着 nav 为 null,并且对 nav 的后续访问会导致 null 引用。
关于javascript - 仅适用于已实现文件中的一项功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6800372/