为了账号安全,请及时绑定邮箱和手机立即绑定

仅在单击时执行脚本

仅在单击时执行脚本

慕妹3242003 2021-10-07 20:16:18
我希望只有在单击某个链接时才刷新页面。但是在我的示例中,脚本是在页面加载时执行的,而不是在单击相应元素时执行。我不是一个 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>
查看完整描述

3 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

您正在执行该功能


(function fun() {


}());  <-- this is executing it

当你定义一个函数时,你就拥有了这个函数


function fun() {


}


查看完整回答
反对 回复 2021-10-07
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

如前所述,

如果您愿意,您也可以使用类似 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")}); 


查看完整回答
反对 回复 2021-10-07
?
潇湘沐

TA贡献1816条经验 获得超6个赞

我认为这是您在 vanilla 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>


查看完整回答
反对 回复 2021-10-07
  • 3 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信