document.queryselectorall没有从生成的html元素接到呼叫
每当用户单击按钮时,我将显示从.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)
})
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您在将元素添加到DOM之前是附加事件。
尝试委派事件
,但最好使用日期属性
maybe you are attach the event BEFORE you added the element to the DOM.
Try to delegate the event
but it's better to use the date attribute
该问题是通过使用ARM144的答案来解决的。将onclick属性附加到跨度
The problem is fixed by using answer from Arm144. Attaching onclick attribute into the span
您分配点击处理程序的跨度为空,因此它们以0宽度渲染,您无法单击它们。
以下内容通过添加内容(非破坏空间)来纠正此问题。
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).
使用jQuery方法的委托单击事件#fortered-items ),然后将单击事件委派给
.icon-xmark
用户单击($(this)
)。这种间接的事件处理方式称为。这是必要的,因为您无法将事件处理程序绑定到动态添加的元素。详细信息在示例中评论
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