在HTML中调用匿名函数 [英] Calling anonymous function in HTML
问题描述
我有一个关于将匿名函数提取到HTML的问题.这是我的HTML代码行:
I have a question on pulling anonymous functions to an HTML. This is my HTML line of code:
onclick="functionToPull('map')"
functionToPull如果不是匿名的,则为函数的名称.如何提取匿名javascript函数?
functionToPull would be the name of the function if it was not anonymous. How do I pull an anonymous javascript function?
示例:
(function (){
})();
推荐答案
将事件处理程序放入click事件被认为是不好的做法,除了Angular之类的框架.推荐的方法是像这样创建一个事件处理程序,
Putting your event handler in the click event is considered a bad practice, except for frameworks like Angular. The recommended approach would be to create an event handler like so,
document.getElementById("myElement").addEventListener("click", function(){ alert("Hello World!"); });
但是,如果您真的想那样做,这就是您想要的:
But if you really want to do it that way, here's what you wanted:
<body>
<button onclick='(function(){ console.log("Hello World"); })();'></button>
</body>
您可以在此监听器中查看它的运行情况.匿名函数监听器
You can see it in action in this plunker.anonymous function plunker
这篇关于在HTML中调用匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!