如何为多个 div 的内部/外部创建"点击"事件条件 - JavaScript?
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/14 11:56:17
您可以使用事件侦听器来监听点击。
示例
以下是代码 −
<!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>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
<div class="divDemo">
第一部分
</div>
<div class="divDemo">
第二部分
</div>
</body>
<script>
document.addEventListener('click', callEventFuncion)
function callEventFuncion(event) {
var div = document.querySelectorAll('.divDemo');
var titleResult = document.querySelectorAll('.my-title');
var result = Array.apply(0, div).find((v) => v.contains(event.target));
if (result) {
console.log(" 增加分区选择");
}
else {
console.log(" 仅增加 DIV 外部的元素");
}
}
</script>
</html>
要运行上述程序,请保存文件名"anyName.html(index.html)"。右键单击该文件并选择选项"使用 Live Server 打开"在 Visual Studio Code 编辑器中。
输出
这将在控制台上产生以下输出 −

每当我们单击除法时,它都会增加除法部分,否则它将在除法之外增加。
案例 1
当用户单击 div 部分时。在这里,我单击了 div 部分两次。快照如下 −

控制台中的输出 −

案例 2
现在,我在 div 部分外单击七次。快照如下 −
这将在控制台中产生以下输出 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

