Jquery .on(“click”)函数只触发一次

时间:2015-10-01 04:01:36

标签: javascript jquery html

我注意到这里有很多类似的问题,但他们的解决方案似乎没有用。我附加到按钮元素的click事件只触发一次。有什么想法吗?

我的HTML

<p id="randomCatchphrase">Hello, my name is Inigo Montoya. You killed my father. Prepare to die.</p>
<p id="catch"><button class="catchbutton">Catchphrase me!</button></p>

      

我的JS

$(function() {
    var catchphraseArray = [
        "Good morning, Vietnam!",
        "Khaaaaan!",
        "Bueller...Bueller...Bueller?",
        "Alrighty then!",
        "I know kung fu.",
        "YOU SHALL NOT PASS!",
        "You can't handle the truth!"
    ];

    function getRandomArrayElement(myArray) {
        var randomNumber = Math.floor(Math.random() * myArray.length);
        return myArray[randomNumber];
    }
    var randomPhrase = getRandomArrayElement(catchphraseArray);

    $("#catch").on("click", ".catchbutton", function() {
        $("#randomCatchphrase").text(randomPhrase)
    });
});

2 个答案:

答案 0 :(得分:3)

您的click事件多次启动,但未查看,因为randomPhrase的值未更改(具有第一次声明的值),你需要在click处理程序中调用函数,以便在按下按钮时更新这些值,如下所示:

$("#catch").on("click", ".catchbutton", function() {
  // here the value will updated anytime when button was clicked
  var randomPhrase = getRandomArrayElement(catchphraseArray);
  $("#randomCatchphrase").text(randomPhrase);
});

答案 1 :(得分:2)

randomPhrase未调用getRandomArrayElement,但将单个调用返回getRandomArrayElement保存为变量randomPhrase

$("#catch").on("click", ".catchbutton", function(){
  $("#randomCatchphrase").text(getRandomArrayElement(catchphraseArray);
});