我注意到这里有很多类似的问题,但他们的解决方案似乎不起作用。我附加到按钮元素的单击事件仅触发一次。有什么想法吗?
我的 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)
});
});
最佳答案
您的 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);
});
关于javascript - Jquery .on ("click") 函数仅触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879237/