仅在单击时执行脚本

我希望只有在单击某个链接时才刷新页面。但是在我的示例中,脚本是在页面加载时执行的,而不是在单击相应元素时执行。


我不是一个 js 编码员,而是一个完整的菜鸟......所以请耐心等待我。任何帮助将不胜感激...


编辑:编辑 - 现在我的代码看起来像这样:问题是它根本不再执行,不是在页面加载时,也不是在点击时


编辑 2:它实际上是一个更大问题的一部分:如果你访问这个网站,你可以看到效果:https : //www.klangidee.de/index.php?19start&lang=en


然后使用“制作”下拉菜单并单击“Edition Klangidee”。页面加载正常并跳转到锚点。现在,如果您第二次单击“Edition Klangidee”链接,cookie-bar 似乎将所有内容向上推高了它自己的高度。如果您重新加载,一切都会恢复正常。


cookie-bar 是由我没有写(不能这样做)但下载的脚本创建的。


所以恕我直言,解决它的正确方法是编辑 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>


慕妹3242003
浏览 155回答 3
3回答

慕运维8079593

您正在执行该功能(function fun() {}());&nbsp; <-- this is executing it当你定义一个函数时,你就拥有了这个函数function fun() {}

红颜莎娜

如前所述,如果您愿意,您也可以使用类似 html 的内容执行函数本身<input type="button" onclick="fun()" value="test">javascript&nbsp;fun=()=>{&nbsp; &nbsp;alert("hey there");&nbsp; &nbsp;}或者您可以删除 onclick 并创建这样的事件侦听器html<input id="testBTN" type="button" value="test">javascriptdocument.getElementById("testBTN").addEventListener("click", ()=>{alert("hey man")});&nbsp;

潇湘沐

我认为这是您在 vanilla JS 中寻找的解决方案:&nbsp; &nbsp; window.onload = function(e){&nbsp; &nbsp; &nbsp; &nbsp; console.log("window.onload: " + new Date());&nbsp; &nbsp; }&nbsp; &nbsp; function fun() {&nbsp; &nbsp; &nbsp; &nbsp; location.reload();&nbsp; &nbsp; }<a href="javascript:void(0);" target="_self" id="ek_reload" onclick="fun()">MyMenuItem</a>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript