Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数只触发一次_Javascript_Jquery_Html - Fatal编程技术网

Javascript 函数只触发一次

Javascript 函数只触发一次,javascript,jquery,html,Javascript,Jquery,Html,我注意到这里有很多类似的问题,但他们的解决方案似乎不起作用。我附加到button元素的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 m

我注意到这里有很多类似的问题,但他们的解决方案似乎不起作用。我附加到button元素的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>

randomPhase
不是调用
getRandomArrayElement
,而是返回对
getRandomArrayElement
另存为变量的
randomPhase

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

randomPhase
不是调用
getRandomArrayElement
,而是返回对
getRandomArrayElement
另存为变量的
randomPhase

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

您的
click
事件确实多次触发,但没有看到它,因为
randomPhase
的值没有更改(第一次声明有值),您需要调用
click
处理程序中的函数,以便在按下按钮时随时更新这些值,如下所示:

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

您的
click
事件确实多次触发,但没有看到它,因为
randomPhase
的值没有更改(第一次声明有值),您需要调用
click
处理程序中的函数,以便在按下按钮时随时更新这些值,如下所示:

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