js 自定义事件
Posted 小小高
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 自定义事件相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html> <head lang="zh-CN"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title></title> <style> .button { width: 200px; height: 200px; background-color: antiquewhite; margin: 20px; text-align: center; line-height: 200px; } </style> </head> <body> <div class="button">Button</div> <script> "use strict"; var btn = document.querySelector(‘.button‘); var ev = new Event(‘test‘, { bubbles: ‘true‘, cancelable: ‘true‘ }); btn.addEventListener(‘test‘, function (event) { console.log(event.bubbles); console.log(event.cancelable); console.log(event.detail); }, false); btn.dispatchEvent(ev); </script> </body> </html>
<!DOCTYPE html> <html> <head lang="zh-CN"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title></title> <style> .button { width: 200px; height: 200px; background-color: antiquewhite; margin: 20px; text-align: center; line-height: 200px; } </style> </head> <body> <div class="button">Button</div> <script> "use strict"; var btn = document.querySelector(‘.button‘); var ev = new CustomEvent(‘test‘, { bubbles: ‘true‘, cancelable: ‘true‘, detail: ‘tcstory‘ }); btn.addEventListener(‘test‘, function (event) { console.log(event.bubbles); console.log(event.cancelable); console.log(event.detail); }, false); btn.dispatchEvent(ev); </script> </body> </html>
以上是关于js 自定义事件的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段12——JavaScript的Promise对象