函数在页面加载时调用两次或仅在刷新时调用

时间:2021-05-06 22:57:19

标签: javascript html jquery pageload

我在使用此功能时遇到问题。由于我不知道的原因,它会在页面加载或刷新时触发两次。我尝试寻找适合我情况的东西,但 document.addEventListener("DOMContentLoaded", function())window.addEventListener... 都没有做任何事情,只会导致进一步的头发撕裂。如果这会影响我的结果,该网站目前使用 Node.js 位于本地主机上。

我对 JavaScript 还很陌生,所以如果原因很明显,我深表歉意。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
$(document).ready(function () {
  setTimeout(function() {
  alert("Congratulations! As our x customer, you've just got a 100% discount on your cart\n developer 
  note, fill x with specified amount from management")
      var myDiv = document.getElementById('theDiv');
      myDiv.style.display = myDiv.style.display === 'none' ? 'block' : 'none';
  }, 1000)
})
</script>

我做了一个替代版本,但这只会在页面刷新时触发。不是来自另一个页面。

window.onload = function() {
  setTimeout(function() {
  alert("Congratulations! As our x customer, you've just got a 100% discount on your cart\n developer note, fill x with specified amount from management")
  var myDiv = document.getElementById('theDiv');
  myDiv.style.display = myDiv.style.display === 'none' ? 'block' : 'none';
}, 1000)}

这是它正在更改的 div,如果这与它有关。

<div id="theDiv" style={{"display":"none"}}>Total after discount: <div 
style={{ "text-decoration": "line-through","display": "inline"}}> {getTotal().toString()}</div> {'->'} 
{priceReductionForRandomCustomer()} kr</div>

1 个答案:

答案 0 :(得分:0)

有两个问题。

在第一个代码片段中,您发送给 alert() 的字符串被分成两行。

第二个问题是您在 <script> 标记中包含了 JavaScript 代码,该标记也具有 src='' 属性。

将您的代码放在它自己的脚本标签中,如下所示:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Hey</title>
  </head>
  <body>
    <div id="theDiv"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
      setTimeout(function() {
          alert("Congratulations! As our x customer, you've just got a 100% discount on your cart\n developer note, fill x with specified amount from management")
          var myDiv = document.getElementById('theDiv');
          if (myDiv !== undefined) {
            myDiv.style.display = myDiv.style.display === 'none' ? 'block' : 'none';
          }
      }, 1000)
    })
    </script>
  </body>
</html>

相关问题