我可以使用Href链接到我网站上的页面并在加载时执行函数吗。我不希望函数自动加载(而且这很容易做到(,因为有多种方法可以进入页面。
<div onclick="location.href='index.html'; hideshow(blog-post-grundig)">
上面的链接将带您进入页面,我希望在加载该页面时在该页面上执行该功能,请参阅下面的功能:
function hideshow(btn) {
var a = document.querySelectorAll('[id^="blog-post"]');
a.forEach(a => {
if (a.id == btn) a.style.display = "block";
if (a.id != btn) a.style.display = "none";
})
}
如有任何帮助,我们将不胜感激。
不,不能这样做-JS只在当前页面上执行。
你应该为此使用一个锚:
<a href="index.html#blog-post-grundig">
然后在index.html上,在加载时检查location.hash
,并在引用博客文章时自动执行该函数。
您可以向href添加一个查询字符串,这将是函数的Id
示例
// this object will containe all functions that you will be executing.
var functions = { hideshow:function(btn) {
var a = document.querySelectorAll('[id^="blog-post"]');
a.forEach(a => {
if (a.id == btn) a.style.display = "block";
if (a.id != btn) a.style.display = "none";
})
}
}
// now when the page load
function load(){
const urlParams = new URLSearchParams(window.location.search);
const f = urlParams.get('f'); // which will be extracted from index.html?f=hideshow And that will be 'hideshow'
functions[f]("somthing")
}
load();
<div onclick="index.html?f=hideshow">