是否有任何方法使用onclick html属性调用多个JavaScript函数?
当前回答
var btn = document.querySelector('#twofuns'); btn.addEventListener(“点击”,method1); btn.addEventListener(“点击”,method2); 函数method2 () { console.log(方法2); } 函数method1 () { console.log(方法1); } <!DOCTYPE html > < html > < >头 < meta charset = " utf - 8 " > <meta name="viewport" content="width=device-width"> <标题> Pramod Kharade-Javascript < /名称> > < /头 身体< > <button id="twofuns">点击我!< /按钮> 身体< / > < / html >
您可以使用一个或多个方法实现/调用一个事件。
其他回答
功能组件
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
当然,只需将多个侦听器绑定到它。
jQuery速成
$(“#id”).bind(“click”, function() { 警报(“事件 1”); }); $(“.foo”).bind(“click”, function() { 警报(“Foo 类”); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <div class=“foo” id=“id”>Click</div>
另外,为了便于维护JavaScript,可以使用命名函数。
下面是匿名函数的例子:
var el = document.getElementById('id');
// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });
但是,想象一下,您有一对附加到同一个元素上的它们,并且想要删除其中一个。从该事件侦听器中删除单个匿名函数是不可能的。
相反,你可以使用命名函数:
var el = document.getElementById('id');
// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };
// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);
// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);
这也使您的代码更容易阅读和维护。特别是当函数更大的时候。
您可以将所有函数组合成一个并调用它们。像Ramdajs这样的库具有将多个函数组合成一个函数的功能。
<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>
或者你可以把合成作为一个单独的函数在js文件中调用它
const newFunction = R.compose(fn1,fn2,fn3);
<a href="#" onclick="newFunction()">Click me To fire some functions</a>
下面是另一个答案,它将单击事件附加到.js文件中的DOM节点。它有一个函数callAll,用于调用每个函数:
const btn = document.querySelector('.btn'); const callAll = (fn) = > (……args) = > fn。forEach(fn => fn?.(…args)); 函数logHello() { console.log('你好'); } 函数logBye() { console.log('再见'); } btn.addEventListener(“点击”, callAll (logHello logBye) ); <button type="button" class="btn"> 点击我 < /按钮>
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- 防止滚动条增加到Chrome页面的宽度
- 使用图像而不是单选按钮
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 我可以嵌套一个<按钮>元素内< >使用HTML5?
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- 设置TextView文本从html格式的字符串资源在XML
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误