[英]How to enable and disable document event handler (specifically click)
我有一个按钮,点击它,我必须在整个文档上启用 click 事件处理程序。 一旦有人现在点击,我想捕获该元素的 dom 选择器并再次禁用事件处理程序。
这个问题是不是已经问过了? 我搜索了很多,但找不到任何相关的东西。 在特定元素上启用或禁用事件处理程序有很多解决方案,但我必须对整个文档执行此操作。 这是我的代码 -
JavaScript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
element.style.backgroundColor = "#FDFF47";
var text = $(event.target).text();
console.log(text) //This text should be the DOM Selector, which I'm not able to retrieve
select_target = false
}
})
$('.select_target').click(function() {
select_target = true
})
</script>
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
这给了我Select Target
作为 output 而不是元素的 DOM 选择器,我一开始没想到它会成为目标按钮,但无论我在点击 Z99938282F040161859941E18F0718592ZEFCF4 目标按钮后点击什么。
我知道代码看起来很笨拙,但我们将不胜感激。 谢谢!
看起来下面的代码符合我的预期。 它适用于希望发生类似事情的每个人,即为了能够 select 页面中的元素,您希望使用干净且可修改的代码在其上执行特定操作。
Javascript -
<script>
var select_target = false;
$(document).click(function(event) {
if (select_target) {
event.preventDefault(); //If you click a link or a button, this helps in just selecting it and it won't perform it's default operation.
var text = $(event.target).text();
console.log(text)
select_target = false;
}
})
$(document).ready(function() {
$("body *").mouseenter(function(el){
if(select_target){
$(el.target).addClass("red-hover-box"); //To highlight the elements on hover
}
})
$("body *").mouseout(function(el){
if(select_target){
$(el.target).removeClass("red-hover-box"); //To remove the highlight on the elements. This will keep the element highlighted if you click on it, since the select_target's value would be false after the click.
}
})
})
$('.select_target').click(function() {
e.stopPropagation(); //To prevent the click on the button to be handled by the event listener.
select_target = true
})
</script>
CSS -
.red-hover-box{
border:1px solid red;
}
HTML -
<!-- Lot of code from the other parts of the webpage -->
<button name="ignore" type="button" class="btn btn-primary btn-md m-1 select_target">
Select Target
</button>
<!-- Lot of code from the other parts of the webpage -->
我现在仍然能够弄清楚如何获取已单击的 HTML 元素的唯一标识符,并且一旦弄清楚就会更新此答案。
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.