Javascript在页面刷新后工作,不知道解决方案

Javascript works after page refresh, not knowing the solution

本文关键字:工作 不知道 解决方案 刷新 Javascript      更新时间:2023-09-26

我在custom.js文件中有这两个非常简单的javascript。

问题是它仅在页面刷新后才能工作。

现在它在正文标签中。我应该放在哪里?我该如何解决使其正常工作(而不是手动刷新站点)。我试过(文档).ready,但仍然不起作用。

我的网页

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript" src="http://nosolution.com/js/custom.js"></script>
<span class="underline">Text</span>
<button>Change</button>
<span class="underline">Text</span>
<button class="hid">Change</button>

我的脚本

   $(document).on('pageinit',function(){
      $("button").click(function(){
         $("span.underline").addClass("underlined");
      });
     $("button.hid").click(function(){
        $("span.underline").removeClass("underlined");
     });
});

非常感谢您的帮助。

你可以试试这个:

$(document).ready(function(){
    $(document).on('click', 'button', function(){
        $("span.underline").addClass("underlined");
    });
    $(document).on('click', 'button.hid', function(){
        $("span.underline").removeClass("underlined");
    });
});

Mike C.是正确的。 您的代码应按以下方式形成:

$(document).ready(function(){
    $("button").click(function(){
        $("span.underline").addClass("underlined");
    });
    $("button.hid").click(function(){
        $("span.underline").removeClass("underlined");
    });
});
相关文章: