document.queryselectorall没有从生成的html元素接到呼叫

发布于 2025-02-11 10:02:01 字数 1458 浏览 3 评论 0 原文

每当用户单击按钮时,我将显示从.html函数生成的DIV元素列表。该代码看起来像下面的

array

const obj = [{"id":"1","section":"delivery","label":"Self-Pick up"},{"id":"2","section":"delivery","label":"Delivery"}]

javaScript

createFilterBubblesTemplate = (obj) => {
  let bubbles = ''
  obj.forEach(e => {
    bubbles += `<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`
  })
  $("#filtered-items").html(bubbles);
}

html元素在由 createfilterbblestemplate生成后函数函数

<div class="filter-items" id="filtered-items">
    <div class="filter-btn">
    <span>Self-Pick up</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="1" data-filter-section="delivery"></span>
    </div><div class="filter-btn">
    <span>Delivery</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="2" data-filter-section="delivery"></span>
    </div>
</div>

在class =“ icon-xmark”的跨度上,它似乎不起作用。需要帮助来解决这个问题

document.querySelectorAll('.icon-xmark').forEach(item => {
  item.addEventListener('click', (event) => {
    console.log(event)
  })
})

I'm displaying list of div element that generated from .html function whenever users click a button. The code look like below

array

const obj = [{"id":"1","section":"delivery","label":"Self-Pick up"},{"id":"2","section":"delivery","label":"Delivery"}]

javascript

createFilterBubblesTemplate = (obj) => {
  let bubbles = ''
  obj.forEach(e => {
    bubbles += `<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`
  })
  $("#filtered-items").html(bubbles);
}

html element after generated by createFilterBubblesTemplate function

<div class="filter-items" id="filtered-items">
    <div class="filter-btn">
    <span>Self-Pick up</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="1" data-filter-section="delivery"></span>
    </div><div class="filter-btn">
    <span>Delivery</span>
    <span class="icon-xmark" id="bubbles-close" data-filter-id="2" data-filter-section="delivery"></span>
    </div>
</div>

But when I tried to attach click eventlistener on span with class="icon-xmark", its seems not working. Need help to solve this issue

document.querySelectorAll('.icon-xmark').forEach(item => {
  item.addEventListener('click', (event) => {
    console.log(event)
  })
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冷月断魂刀 2025-02-18 10:02:01

也许您在将元素添加到DOM之前是附加事件。
尝试委派事件

document.addEventListener('click', (event) => {
  const target = event.target;
  if (target.classList.contains('icon-xmark')) {
    console.log(event);
  }
});

,但最好使用日期属性

<span class="icon-xmark" data-close id="bubbles-close" data-filter-id="2" data-filter-section="delivery"></span>
  ...
document.addEventListener('click', (event) => {
  const target = event.target;
  if ('close' in target.dataset) {
    console.log(event);
  }
});

maybe you are attach the event BEFORE you added the element to the DOM.
Try to delegate the event

document.addEventListener('click', (event) => {
  const target = event.target;
  if (target.classList.contains('icon-xmark')) {
    console.log(event);
  }
});

but it's better to use the date attribute

<span class="icon-xmark" data-close id="bubbles-close" data-filter-id="2" data-filter-section="delivery"></span>
  ...
document.addEventListener('click', (event) => {
  const target = event.target;
  if ('close' in target.dataset) {
    console.log(event);
  }
});
燕归巢 2025-02-18 10:02:01

该问题是通过使用ARM144的答案来解决的。将onclick属性附加到跨度

createFilterBubblesTemplate = async (obj) => {
  let bubbles = ''
  obj.forEach(e => {
    bubbles += `<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" onclick="closeFiltersBubbles(${e.id},'${e.section}')" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`
  })
  $("#filtered-items").html(bubbles);
}

The problem is fixed by using answer from Arm144. Attaching onclick attribute into the span

createFilterBubblesTemplate = async (obj) => {
  let bubbles = ''
  obj.forEach(e => {
    bubbles += `<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" onclick="closeFiltersBubbles(${e.id},'${e.section}')" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`
  })
  $("#filtered-items").html(bubbles);
}
烂柯人 2025-02-18 10:02:01

您分配点击处理程序的跨度为空,因此它们以0宽度渲染,您无法单击它们。

以下内容通过添加内容(非破坏空间)来纠正此问题。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type"   content="text/html;charset=utf-8">
        <meta http-equiv="expires"        content="0">
        <meta http-equiv="cache-control"  content="private">
        <meta http-equiv="pragma"         content="no-cache">
        <title>SO - Bitmap (svg)</title>
        <!--
        -->
        <style type="text/css">
            body {
                background-color:   #eee;
            }
            
            .icon-xmark {
                background-color:   lime;
                cursor:             pointer;
            }
        </style>
        <script>
            const obj = [{"id":"1","section":"delivery","label":"Self-Pick up"},{"id":"2","section":"delivery","label":"Delivery"}];
            
            let createFilterBubblesTemplate = (obj) => {
              let bubbles = '';
              obj.forEach(e => {
                bubbles += `<div class="filter-btn">
                <span>${e.label}</span>
                <span class="icon-xmark" id="bubbles-close" data-filter-id="${e.id}" data-filter-section="${e.section}">    </span>
                </div>`;
              });
              document.querySelector("#filtered-items").innerHTML = bubbles;
            }; //   createFilterBubblesTemplate
                              
            document.addEventListener('DOMContentLoaded', () => {
                setTimeout ( () => {
                        createFilterBubblesTemplate(obj);
                        setTimeout ( () => {
                                document.querySelectorAll('.icon-xmark').forEach(item => {
                                    item.addEventListener('click', (event) => {
                                        console.log('Here we go...');
                                    });
                                });
                            } 
                          , 1000
                        );
                    }
                  , 1000
                );
            });
        </script>
    </head>
    <body>
        <div class="filter-items" id="filtered-items"></div>
    </body>
</html>

The spans you assign the click handler to are empty, thus they are rendered with 0 width and you cannot click them.

The following corrects this by adding content (non-breaking spaces).

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type"   content="text/html;charset=utf-8">
        <meta http-equiv="expires"        content="0">
        <meta http-equiv="cache-control"  content="private">
        <meta http-equiv="pragma"         content="no-cache">
        <title>SO - Bitmap (svg)</title>
        <!--
        -->
        <style type="text/css">
            body {
                background-color:   #eee;
            }
            
            .icon-xmark {
                background-color:   lime;
                cursor:             pointer;
            }
        </style>
        <script>
            const obj = [{"id":"1","section":"delivery","label":"Self-Pick up"},{"id":"2","section":"delivery","label":"Delivery"}];
            
            let createFilterBubblesTemplate = (obj) => {
              let bubbles = '';
              obj.forEach(e => {
                bubbles += `<div class="filter-btn">
                <span>${e.label}</span>
                <span class="icon-xmark" id="bubbles-close" data-filter-id="${e.id}" data-filter-section="${e.section}">    </span>
                </div>`;
              });
              document.querySelector("#filtered-items").innerHTML = bubbles;
            }; //   createFilterBubblesTemplate
                              
            document.addEventListener('DOMContentLoaded', () => {
                setTimeout ( () => {
                        createFilterBubblesTemplate(obj);
                        setTimeout ( () => {
                                document.querySelectorAll('.icon-xmark').forEach(item => {
                                    item.addEventListener('click', (event) => {
                                        console.log('Here we go...');
                                    });
                                });
                            } 
                          , 1000
                        );
                    }
                  , 1000
                );
            });
        </script>
    </head>
    <body>
        <div class="filter-items" id="filtered-items"></div>
    </body>
</html>

最舍不得你 2025-02-18 10:02:01

使用jQuery方法的委托单击事件#fortered-items ),然后将单击事件委派给 .icon-xmark 用户单击( $(this))。这种间接的事件处理方式称为。这是必要的,因为您无法将事件处理程序绑定到动态添加的元素。

详细信息在示例中评论

const obj = [{
  "id": "1",
  "section": "delivery",
  "label": "Self-Pick up"
}, {
  "id": "2",
  "section": "delivery",
  "label": "Delivery"
}]

/*
A proper arrow function should begin with a const or let
`.html()` method is like `.innerHTML` in that it it's destructive
Use `.append()`
*/
const createFilterBubblesTemplate = (obj) => {
  obj.forEach(e => {
    let html =`<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`;
    $("#filtered-items").append(html);
  });
}

/*
Delegate click events to each ".icon-xmark" by binding the click event to
the parent tag "#filtered-items"
Note the second parameter ".icon-xmark" -- that designates "this" as ".icon-xmark"
console.log(event) does nothing
*/
$("#filtered-items").on('click', ".icon-xmark", function(e) {
  const x = $(this).data('filter-id');
  console.log(x);
});

createFilterBubblesTemplate(obj);
.icon-xmark {
  display: inline-block;
  padding: 5px;
  outline: 1px red dashed
}
<div class="filter-items" id="filtered-items"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Delegate click event with jQuery method .on(). Bind the click event to a static element (an element that's been there since the page loaded, like #filtered-items) and then delegate the click event to the .icon-xmark the user clicked ($(this)). This indirect way of event handling is called event delegation. This is necessary since you cannot bind event handlers to dynamically added elements.

Details are commented in example

const obj = [{
  "id": "1",
  "section": "delivery",
  "label": "Self-Pick up"
}, {
  "id": "2",
  "section": "delivery",
  "label": "Delivery"
}]

/*
A proper arrow function should begin with a const or let
`.html()` method is like `.innerHTML` in that it it's destructive
Use `.append()`
*/
const createFilterBubblesTemplate = (obj) => {
  obj.forEach(e => {
    let html =`<div class="filter-btn">
    <span>${e.label}</span>
    <span class="icon-xmark" data-filter-id="${e.id}" data-filter-section="${e.section}"></span>
    </div>`;
    $("#filtered-items").append(html);
  });
}

/*
Delegate click events to each ".icon-xmark" by binding the click event to
the parent tag "#filtered-items"
Note the second parameter ".icon-xmark" -- that designates "this" as ".icon-xmark"
console.log(event) does nothing
*/
$("#filtered-items").on('click', ".icon-xmark", function(e) {
  const x = $(this).data('filter-id');
  console.log(x);
});

createFilterBubblesTemplate(obj);
.icon-xmark {
  display: inline-block;
  padding: 5px;
  outline: 1px red dashed
}
<div class="filter-items" id="filtered-items"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文