我只希望在单击某个链接时刷新页面。但是在我的示例中,脚本是在页面加载时执行的,而不是在单击相应元素时执行的。
我不是JS编码器,而是一个完全菜鸟...所以请耐心等待我。任何帮助将不胜感激...
编辑:已编辑-现在我的代码如下: 问题在于,它不再完全执行,不在页面加载上执行,也不再在单击上执行
编辑2:实际上,这是一个更大的问题的一部分:如果您访问以下网站,则可以看到效果:https://www.klangidee.de/index.php?19start&lang=en
然后使用“制作”下拉菜单,然后单击“ Edition Klangidee”。页面加载正常并跳转到锚点。现在,如果您第二次单击“ Edition Klangidee”链接,则cookie栏似乎会将所有内容推高了自己的高度。如果重新加载,一切都会恢复正常。
cookie栏是由我没有写(无法执行)但下载的脚本创建的。
因此,恕我直言,解决该问题的正确方法是编辑js文件。但是由于我没有足够的知识,所以我认为自动重新加载(而不是手动重新加载)将是一种合适的解决方法。
也许背景信息会有所帮助。...
script:
=======
<script type="text/javascript">
;(function fun() {
var reloads = [1000, 3000],
storageKey = 'reloadIndex',
reloadIndex = parseInt(localStorage.getItem(storageKey), 10) || 0;
if (reloadIndex >= reloads.length || isNaN(reloadIndex)) {
localStorage.removeItem(storageKey);
return;
}
setTimeout(function(){
window.location.reload();
}, reloads[reloadIndex]);
localStorage.setItem(storageKey, parseInt(reloadIndex, 10) + 1);
}
</script>
html-code:
==========
<a href="https://mylink#myanchor" target="_self" id="ek_reload" onclick="fun()">MyMenuItem</a>
答案 0 :(得分:3)
(function fun() {
}()); <-- this is executing it
定义功能时,您只需拥有功能
function fun() {
}
答案 1 :(得分:0)
我认为这是您在香草JS中寻找的解决方案:
window.onload = function(e){
console.log("window.onload: " + new Date());
}
function fun() {
location.reload();
}
<a href="javascript:void(0);" target="_self" id="ek_reload" onclick="fun()">MyMenuItem</a>
答案 2 :(得分:0)
如果您愿意,也可以使用类似的方法
html
<input type="button" onclick="fun()" value="test">
javascript
fun=()=>{
alert("hey there");
}
,或者您可以删除onclick并创建事件监听器 这样
html
<input id="testBTN" type="button" value="test">
javascript
document.getElementById("testBTN").addEventListener("click", ()=>{alert("hey man")});
希望我能够提供帮助:)