2 回答

TA贡献1836条经验 获得超3个赞
出现此问题的原因是您动态定义。换句话说,在页面的初始呈现过程中未定义此元素。myfunction1
您可以使用事件委派来修复它。操作方法如下:
不要在 元素上定义回调,而是为具有匹配 css 类的 PARENT 元素的所有子元素定义回调。例如:
$( ".btnContainer .btn" ).on( "click", function( event ) { event.preventDefault(); console.log("clicked"); });
哪里:
<div class='btnContainer'> </div>
现在,当您动态添加带有(类名)的按钮作为 的子级时,它们仍将访问单击处理程序,因为事件处理程序不绑定到 元素 ,而是绑定到它的父级,因此当触发 click 事件时,父级将事件委托给具有匹配类的所有子级!btn
btnContainer
btn

TA贡献1831条经验 获得超9个赞
不要在循环中添加函数
委托
看看这里。有很多问题,我已经解决了其中的几个问题
你可能想做
button.setAttribute("data-code",item.code);
而不是
button.id = i + "-cmd";
// function.js
const content = document.getElementById("content");
content.addEventListener("click",function(e) {
const tgt = e.target, // the element clicked
id = tgt.id; // the ID of the element
if (id.indexOf("-cmd") !=-1) { // is that element one of our buttons?
// get the name of the article from the button - this could also be a data attibute
var pos = id.split("-")[1];
addToCart(pos);
}
})
function chargerArticles() {
const myShoppingCart = catalogArray.map(function(item, i) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
// here would be a good place to add item.name or something
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
content.appendChild(articles) // ???
})
}
function searchInCart(name) {
return myCartArray.filter(function(x) {
return x.name === name
})[0];
}
添加回答
举报