jQuery单击以使用数组标识元素,此数组卡在循环中

yxyvkwin  于 2023-06-29  发布在  jQuery
关注(0)|答案(1)|浏览(85)

这似乎应该是一个简单的解决方案。该代码允许用户单击标题、段落或图像,并标识元素的类型。它工作,但随后陷入了一个无限循环。它似乎在继续尝试运行相同的代码。我读了很多类似的问题,但建议使用。一个或其他方法没有工作。

$(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]);
    };
  });
});
3npbholx

3npbholx1#

这不是对代码错误的另一种解释,而是一种替代方法,我认为这是你的意图:

$(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">

click元素没有附加到*,因为这将导致每次在任何目标元素中观察到单击时触发三个事件(针对 *target元素 * 本身以及bodyhtml元素)。相反,我在父体元素上使用“委托”事件处理,仅限于元素"H1,P,IMG"
多年后回到这个问题,我注意到当然也有一个简单的非jQuery答案:

window.onload=()=>{
  const msgs = {H1:'This is a heading',P: 'This is a paragraph', IMG:'This is an image'};
  document.body.onclick=e=>
    Object.keys(msgs).includes(e.target.tagName) && console.log(msgs[e.target.tagName]);
};
<h1>This is a heading</h1>
<p>a paragraph and below, an image:</p>
<img src="hello.jpg">

相关问题