[英]Dragtable Javascript library isn't working for every page. Only in Index.html where library is imported?
[英]Run function only on index.html page (Javascript)
我有一个函数在我的index.html页面上运行一个随机单词生成器,该函数工作正常,但是当您在任何其他页面上时也可以继续运行(由于windows.onload)。
我不确定如何编写JavaScript以说“仅在index.html上运行此功能,没有其他页面”或“仅在此类上运行”
window.onload = function refreshWord() setInterval(function randomWord() { const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist']; const randomGenerator = Math.floor(Math.random() * words.length); document.getElementById('textswap').innerHTML = words[randomGenerator]; }, 2000);
<div class="col"> <h4>These are the words, a <span class="front-page-text-swap" id="textswap"> person </span>.</h4> </div>
我的最终目标是仅在index.html页面上执行refreshWord()
函数,但是没有其他方法可以执行此操作(我想使用香草js,而不是jQuery)
检查pathname
是否为index.html
,如果是,则创建时间间隔:
if (window.location.pathname === '/index.html') {
setInterval( ...
}
最好只选择一次 textswap
,而不是每次间隔运行一次,并且只创建一个 words
数组,而不是每次都声明一个新数组,这将是很不错的:
if (window.location.pathname === '/index.html') {
const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist'];
const getRandomWord = () => words[Math.floor(Math.random() * words.length)];
const textswap = document.getElementById('textswap');
setInterval(() => {
textswap.textContent = getRandomWord();
});
}
您可以将只想要的代码放在index.html
然后将其从所有页面共享的共享Javascript页面中删除,然后将其放在仅位于index.html
页面HTML中的<script>
标记中,在其他任何页面中:
<script>
// insert this script only in the index.html page and
// directly inserted, not via a separate script file
window.onload = function refreshWord()
setInterval(function randomWord() {
const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist'];
const randomGenerator = Math.floor(Math.random() * words.length);
document.getElementById('textswap').innerHTML = words[randomGenerator];
}, 2000);
</script>
您还可以测试仅存在于index.html
上的页面元素。 因此,如果textswap
元素仅存在于index.html
,则可以执行以下操作:
window.onload = function refreshWord()
var textswap = document.getElementById('textswap');
// see if the textswap element exists in this page
if (textswap) {
setInterval(function randomWord() {
const words = ['Engineer', 'Developer', 'Illustrator', 'Cyclist', 'Artist'];
const randomGenerator = Math.floor(Math.random() * words.length);
textswap.innerHTML = words[randomGenerator];
}, 2000);
}
因此,只有实际存在目标页面唯一的某个元素时,才调用setInterval()
。
这种“内容检测”有时比URL测试更安全,因为它跟踪的是您想要的实际页面,而不是URL(可以在某些时候更改)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.