简体   繁体   English

单击按钮后激活带有参数的javascript函数

[英]Activate javascript function with parameter after button click

 function changeForms(data){ document.getElementById("firstname").value = data.firstName; document.getElementById("lastname").value = data.lastName; document.getElementById("email").value = data.emailAddress; } 

I want to call this function with this button: 我想通过以下按钮调用此函数:

 <button class="button" id="autofill" onclick="">Fill</button> 

My problem is, that the parameter data is from another function, but i dont want to call the changeForms function after the function getData like below: 我的问题是,参数数据来自另一个函数,但是我不想在函数getData之后调用changeForms函数,如下所示:

 function getData(data) { data= data.values[0]; changeForms(data); } 

I want to start the function changeForms after the click, but with the data from getData. 我想在单击后启动功能changeForms,但要使用getData中的数据。 Is it possible to stop a function until a buttonclick or maybe store the data somewhere? 是否可以在单击按钮之前停止功能,或者将数据存储在某个地方?

Thanks in advance 提前致谢

Marcel 马塞尔

first suggestion don't do inline javascript, this looks ugly, hard to maintain and not that flexible. 首先建议不要使用内联JavaScript,这看起来很丑陋,难以维护,而且不够灵活。

I suggest: 我建议:

add to your button an id, like "buttonWithId" then write following javascript code: 向您的按钮添加一个ID(例如“ buttonWithId”),然后编写以下javascript代码:

var myButton = document.getElementById("buttonWithId");
myButton.addEventListener("click", function() {
   // your code goes here....
});

here some docu on this: 这里一些文档:

https://www.w3schools.com/jsref/met_element_addeventlistener.asp https://www.w3schools.com/jsref/met_element_addeventlistener.asp

then you allway can use the return value of your `getData`` 那么您始终可以使用`getData`的返回值

var getData = function() {
    return someData;
}

then the call looks like this: 那么呼叫看起来像这样:

var someData = getData();
changeForms(someData);

put this inside the empty function defined earlier. 将其放入先前定义的空函数中。

Note: if your function getData is async, you have to use a callback function or a promise (my personal favorite choice). 注意:如果函数getData是异步的,则必须使用回调函数或promise(我个人最喜欢的选择)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM