簡體   English   中英

OnClick() 事件在我的代碼中的動態按鈕的 JavaScript 中不起作用

[英]OnClick() event is not working in JavaScript for dynamic button in my code

我使用 JavaScript 在網頁上的 for 循環中添加了一個動態按鈕,並為每個按鈕分配了一個唯一的 ID。 我想將 onclick() 事件監聽器分配給每個按鈕,但是這個 function 沒有分配給任何動態按鈕。 請幫我解決這個問題。 謝謝你。

myfunction()正在工作,但myfunction1()有一些問題。 我在其動態 HTML 中看不到 onclick 事件。 HTML 視圖

有JS文件。 data.js 包含對象的 arrays 和其他包含訪問數據的 function。

// function.js
function chargerArticles() {

  var myShoppingCart = [];



  var articles = document.getElementById("content");
  for (var i = 0; i < catalogArray.length; i++) {


    //Product div
    var article = document.createElement("div");
    article.setAttribute("class", "aa");
    //Unique id
    article.id = i + "-article";

      //Product Name
    var articleName = document.createElement("h4");
    articleName.setAttribute("class", "aa-product-title");
    var articleNameLink=  document.createElement('a');
    articleNameLink.setAttribute('href',"#");
    articleNameLink.innerText = catalogArray[i].name;
    articleName.appendChild(articleNameLink);

    article.appendChild(articleName);

    //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";

    //not working
    button.addEventListener("click", myFunction1);

    function myFunction1() {
      var item = this.getAttribute("id");
      var pos = item.substring(0, 1);
      document.getElementById("1235").innerHTML = "Hello World";
      addToCart(pos);
    }

    //working
    document.getElementById("1234").addEventListener("click", myFunction);

    function myFunction() {
      document.getElementById("1234").innerHTML = "YOU CLICKED ME!";
    }


    zoneCmd.appendChild(button); //child 2
    //zoneCmd child of article element
    article.appendChild(zoneCmd);



    //finally article as a child of articles 
    articles.appendChild(article);
  }
}

function searchInCart(name) //T-Shirt
{
  myShoppingCart = myCartArray;
  var name1 = name;
  var stop = 0;
  for (var i = 0; i < myShoppingCart.length && stop == 0; i++) {
    if (myShoppingCart[i].name == name1) {
      stop = 1;
      // console.log("Hello wooooorld!");
      return true;
    } else {
      return false;
    }
  }

}

function addToCart(pos) {

  if (searchInCart(catalogArray[pos].name)) {
    alert("Already Exist!"); // display string message

  } else {
    var ident = pos + "-qte";
    var quatity = document.getElementById("ident").value;
    if (quatity > 0) {
      var articleCmd = {}; //array of  objects
      articleCmd.name = catalogArray[pos].name;
      articleCmd.price = catalogArray[pos].price;
      articleCmd.qte = quatity;
      articleCmd.priceTotal = articleCmd.price * articleCmd.qte;
      myCartArray.push(articleCmd);

    } else {
      // alert
    }
  }

}


//data.js

// data.js
var catalogArray = [{
    code: 100,
    name: "T Shirt c100",
    desc: "Lorem ipsum, or lipsum as it is sometimes known as",
    price: 150,
    image: "./images/img100.jpg"
  },
  {
    code: 101,
    name: "T Shirt c101",
    desc: "Lorem ipsum, or lipsum as it is sometimes known as",
    price: 250,
    image: "./images/img101.jpg"
  },

];



var myCartArray = [{
    name: "T Shirt c100",
    price: 150,
    qte: 2,
    TotalPrice: 150,
  }

];

出現此問題是因為您動態定義myfunction1 換句話說,這個元素不是在頁面的初始渲染過程中定義的。

您可以使用事件委托來修復它。 方法如下:

不要在元素上定義回調,而是為PARENT元素的所有具有匹配 css class 的子元素定義它。 例如:

     $( ".btnContainer .btn" ).on( "click", function( event ) {
        event.preventDefault();
     console.log("clicked");

    });

在哪里:

 <div class='btnContainer'>
 </div>

現在,當您將帶有(類名btn )的按鈕動態添加為btnContainer的子級時,它們仍然可以訪問單擊處理程序,因為事件處理程序未綁定到元素btn ,而是綁定到它的parent ,因此當單擊事件被觸發時,父級將事件委托給所有具有匹配類的子級!

  1. 不要在循環中添加 function
  2. 代表

看看這里。 有很多問題,我已經解決了其中一些

你可能想做

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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM