[英]How to execute function with arguments, inside another function with Javascript?
我正在尝试使用 Jquery 创建简单的应用程序,但我被卡住了,我有两个基本函数,第一个保存事件,第二个函数,我想调用第一个函数,代码在这里:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <button id="test" onclick="funct1(event,id)">clcik1</button> <button id="test2" onclick="mySecondFunction()">clcik2</button> <script> const funct1 = function myFunction(event,id) { alert(event.target.id); }; function mySecondFunction(){ return funct1() } </script> </body> </html>
问题是,第一个函数保持(事件和 id),因此当我将此函数调用到我的第二个函数时,它会抛出错误。 我想要,当我点击第二个按钮时执行第一个功能......有什么解决方案吗?
您应该将参数传递给 onClick 中的 mySecondFunction,而在 js 中,您应该将其放入 mySecondFunction 并将其传递给funct1。 像这样:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <button id="test" onclick="funct1(event,id)">clcik1</button> <button id="test2" onclick="mySecondFunction(event,id)">clcik2</button> <script> const funct1 = function myFunction(event,id) { alert(event.target.id); }; function mySecondFunction(event,id){ return funct1(event,id) } </script> </body> </html>
您需要将参数传递给您的第二个函数:
const funct1 = function myFunction(event,id) {
alert(event.target.id);
};
function mySecondFunction(e, id){
return funct1(e, id)
}
并在按钮上
<button id="test2" onclick="mySecondFunction(event, id)">clcik2</button>
像这样的东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.