[英]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.