How add function name to handler click? [closed]

て烟熏妆下的殇ゞ 提交于 2019-12-13 03:43:37

问题


I have a button and I have function which should execute on click.

example:

<button id="button1">bla bla</button>

<script>
var justFunctionName = "function1";
var function1 = function()
{
alert("!");
}

$("#button1").click(justFunctionName);

</script>

回答1:


HTML

<button id="button1">bla bla</button>



jQuery

var justFunctionName = "function1";

function function1()
{
    alert("!");
}

$("#button1").on("click", window[justFunctionName]);



See working jsFiddle demo




回答2:


$("#button1").click(justFunctionName);

should be

$("#button1").click(function1);



回答3:


var justFunctionName = "function1";

This is assigning the string function1 to the variable justFunctionName.

If you were to do: console.log('justFunctionName'); you would end up with the following result:

>function1

Therefore this variable assignment is completely irrelevant for what you are hoping to achieve. Instead of just assigning a variable to a function you are assigning a variable to a variable which is assigned to a function.


Now take a look at what you are doing here:

var function1 = function () {
  alert("!");
};

This is assigning a variable function1 to the function doing the alert. In this instance, think of the variable as a reference to the function. In order to have the button trigger the alert, you need to call the reference to the function (in this case function1):

$("#button1").click(function1);


来源:https://stackoverflow.com/questions/21001032/how-add-function-name-to-handler-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!