如何启用和禁用文档事件处理程序(具体点击)

How to enable and disable document event handler (specifically click)

我有一个按钮,单击它,我必须在整个文档上启用单击事件处理程序。现在有人单击后,我想捕获该元素的 dom selector 并再次禁用事件处理程序。

这个问题已经有人问了吗?我搜索了很多但找不到任何相关的东西。有很多关于在特定元素上启用或禁用事件处理程序的解决方案,但我必须在整个文档中执行此操作。这是我的代码 -

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 作为输出,而不是元素的 DOM 选择器,我一开始没想到它会成为目标按钮,但无论我点击什么单击 select 目标按钮。

我知道代码看起来很笨拙,但如有任何帮助,我们将不胜感激。谢谢!

看起来下面的代码符合我的预期。它适用于所有希望发生类似事情的人,即能够 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 元素获取唯一标识符,并会在弄清楚后更新此答案。

谢谢!