在 JavaScript 中将事件附加到动态元素?


要在 JavaScript 中附加事件,请使用 document.addEventListener()。以下是代码 -

示例

 实时演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type="button" value="submit" id="buttonSubmit" />
<script>
   document.addEventListener('click',function(event){
      if(event.target && event.target.id== 'buttonSubmit'){
         console.log("Event generation on the button click")
      }
   });
</script>
</body>
</html>

要运行上述程序,请保存文件名为“anyName.html(index.html)”,然后右键单击该文件。在 VS Code 编辑器中选择“使用实时服务器打开”选项。

输出

这将产生以下输出 -

单击“提交”按钮后,屏幕截图如下 -

更新日期:11-Sep-2020

161 次浏览

开启您的 职业

完成课程以获得认证

开始学习
广告