如何在 jQuery 中隐式模拟 click() 事件?

jqueryweb developmentfront end technology

要隐式模拟 click() 事件,您可以内部调用一个函数。

示例

以下代码隐式模拟 click() 事件。

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <div id='demo1'>My Name is John Doe</div>
   <div id='demo2'></div>
   <div id='output'></div>
</body>
<script>
   demo1Data = document.getElementById('demo1').innerHTML
   demo1Data = demo1Data.replace('My Name is John Doe', `<span onclick="replaceData()">My Favourite Subject is JavaScript..</span>`)
   document.getElementById('demo2').innerHTML = demo1Data
   function replaceData() {
      document.getElementById('output').innerHTML = 'I live is US.';
   }
document.getElementById('demo2').querySelector('span').click();
</script>
</html>

要运行上述程序,请将文件另存为 anyName.html(或 index.html)。右键单击该文件,然后在 VS Code 编辑器中选择"使用 Live Server 打开"选项。

输出

输出如下 −


相关文章