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];
}
添加回答
舉報