【问题标题】:JQuery click to identify element using array stuck in loopJQuery单击以使用陷入循环的数组来识别元素
【发布时间】:2021-08-25 02:41:23
【问题描述】:

这看起来应该很容易解决。该代码允许用户单击标题、段落或图像,并识别元素的类型。它可以工作,但随后陷入无限循环。它似乎在继续尝试运行相同的代码。我阅读了很多类似的问题,但使用 .one 或其他方法的建议没有奏效。

$(document).ready(function() {
  
  const elementsToMatch = ['h1', 'p' , 'img']
  const elementsMessage = ['This is a heading', 'This is a paragraph' , 'This is an image']

  $('*').click(function(e) {
    const target = $(e.target)
    elementsToMatch.forEach(function(element, index) {
      
    if (target.is(element, index)) {
      alert(elementsMessage[index]);
    };
  });
});

【问题讨论】:

  • 你查看this 的帖子了吗?
  • 根据@swati 的链接,我尝试了.off().one().unbind(),但在我到达.stopPropagation()event.stopImmediatePropagation() 之前没有任何效果
  • 我不明白为什么传播会导致点击事件重复 3 次,尽管页面上有多少元素(尽管点击背景只会产生一个事件)。
  • @Kinglish 使用 ``` $('*').click(function(e) { event.stopPropagation()``` 确实有效。非常感谢
  • 这能回答你的问题吗? jQuery click events firing multiple times

标签: jquery arrays alert infinite-loop


【解决方案1】:

这不是对您的代码出了什么问题的另一种解释,而是另一种方式来做 - 我认为 - 你的意图:

$(document).ready(function() {
  const msgs = {H1:'This is a heading',P: 'This is a paragraph', IMG:'This is an image'};
  $('body').on("click","H1,P,IMG",function(e) {
  console.log(msgs[this.tagName]);
  });
});
<script src=" https://code.jquery.com/jquery-3.6.0.min.js"></script>
<h1>This is a heading</h1>
<p>a paragraph and below, an image:</p>
<img src="hello.jpg">

点击元素未附加到*,因为这将导致每次在任何目标元素中观察到点击时触发三个事件(对于目标元素本身以及对于bodyhtml 元素)。相反,我在父 body 元素上使用“委托”事件处理,仅限于元素 "H1,P,IMG"

【讨论】:

    猜你喜欢
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2017-03-30
    • 2015-08-16
    相关资源
    最近更新 更多