javascript - onclick 不断调用 javascript 函数

标签 javascript html onclick

HTML:

<div class="container-fluid">
  <div class = "row text-center" align = "middle">
    <h2>Pseudo Random Quote Machine</h2>
  </div>
  <div class = "row text-center" align = "middle">
    <div class = "col-xs-12 well message" id = "quoting"> 
    </div>
  </div>
  <div class = "row text-center" align = "middle">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Random Quote
      </button> 
      <button id = "tweet" class = btn btn-primary>Tweet this!
      </button>
    </div>
  </div>
</div>

Javascript:

function randomQuotes() 
{ 
  //array of quotes
  var quotes = [ "\"Operator! Give me the number for 911!\" - Homer J. Simpson", "\"I\'m normally not a praying man, but if you\'re up there, please save me Superman\" - Homer J. Simpson", "\"I\'m in no condition to drive...wait! I shouldn\'t listen to myself, I\'m drunk!\" - Homer J. Simpson", "\"A Degenerate, Am I? Well You Are A Festizo. See, I Can Make Up Words Too, Sister\" - Peter Griffen", "\"Victory Shall Be Mine!\" - Stewie Griffen", "\"He's a spy, blow him up. I'm gonna go take a shit.\" - Rick Sanchez", "\"Ohh yea, you gotta get schwifty. \" - Rick Sanchez", "\"Yo! What up my glip glops!\" - Rick Sanchez", "\"WUBBA LUBBA DUB DUBS!!! \" - Rick Sanchez", "\"Existence is pain to a meeseeks Jerry, and we will do anything to alleviate that pain.\" - Mr. Meeseeks", " \"It\'s morphine time\" - TheRussianBadger"]; 

  var randNum = Math.floor((Math.random() * quotes.length));
  document.getElementById("quoting").innerHTML = quotes[randNum];
}

function tweetThis()
{
  var tweetToShare = document.getElementById("quoting").innerHTML;
  var tweetUrl = 'https://twitter.com/share?text=' +   encodeURIComponent(tweetToShare) + ".";
  window.open(tweetUrl);
}

document.getElementById("getMessage").onclick = function(){randomQuotes();}
document.getElementById("tweet").onclick = function(){tweetThis();}

基本上,每当我单击两个按钮中的任何一个时,该函数都会被一遍又一遍地调用。这是代码running in Code Pen

我想我的问题是:

  1. 为什么这些函数会被调用多次?

  2. 我应该怎样做才能阻止函数被多次调用或从一开始就阻止它发生?

最佳答案

函数在 chrome 上似乎只被调用一次。也许您的浏览器缓存了旧脚本:maiusc+f5 进行清理

关于javascript - onclick 不断调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44232331/

相关文章:

javascript - 读取拖放文件

android - 包含 Google adsense 广告时如何隐藏 div?

Javascript:更改第一个子样式

javascript - 在不同的按钮中调用相同的函数,并且两者都在 Reactjs、javascript 中给出不同的输出?

javascript - 如何根据某些条件禁用剑道网格单元内的按钮?

javascript - DC.js compositeChart 与两个 lineChart 都代表日期的平均值

javascript - 获取原始utf8字符串

javascript - 将切换的 div 的高度设置为百分比

javascript - 在新窗口中打开 DIV 按钮

android - 如何将 onClick 从 view pager 传递到它下面的 View ?