是否有任何方法使用onclick html属性调用多个JavaScript函数?
当前回答
下面是另一个答案,它将单击事件附加到.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"> 点击我 < /按钮>
其他回答
这是brad的另一种回答,你可以这样用逗号
onclick="funA(), funB(), ..."
但是最好不要使用这种方法-对于小型项目,你可以只在一个函数调用的情况下使用onclick(更多:更新的不显眼的javascript)。
函数funA() { console.log (' A '); } 函数funB(点击元素){ console.log('B: ' + click . innertext); } 函数funC(cilckEvent) { console.log('C: ' + cilckEvent.timeStamp); } div{光标:指针} <div onclick="funA(), funB(this), funC(event)"< / div > >点击我
onclick="doSomething();doSomethingElse();"
但实际上,最好完全不使用onclick,而是通过Javascript代码将事件处理程序附加到DOM节点。这就是所谓的不显眼的javascript。
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
这对我来说很有用,你可以在一个函数中调用多个函数。然后调用这个函数。
另外,为了便于维护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>
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?