2017-05-28 119 views
0

HTML:的onclick不斷調用javascript函數

<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. 我應該怎麼做才能阻止函數被多次調用或阻止它首先發生?

+0

在Chrome 58上正常工作。 – yuriy636

+0

是的,在Firefox上也很好用。53. – Andreas

+0

@cancer,你是對的。謝謝。 – manny

回答

1

函數似乎只在Chrome上調用一次。也許你的瀏覽器緩存一箇舊腳本:maiusc + f5清理

+0

發生這種情況的一種常見方式是,如果您在Chrome上打開了開發人員工具,並且仍在使用Js文件。在chrome上打開開發者工具來啓用緩存,你可以通過去開發者工具 - >網絡 - >禁用緩存來解決這個問題 –