简体   繁体   English

OnClick() 事件在我的代码中的动态按钮的 JavaScript 中不起作用

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

I have added a dynamic buttons inside for loop on webpage using JavaScript and assigned a unique id to each button.我使用 JavaScript 在网页上的 for 循环中添加了一个动态按钮,并为每个按钮分配了一个唯一的 ID。 I wants to assign onclick() event Listener to each button but this function is not being assigned to any of dynamic buttons.我想将 onclick() 事件监听器分配给每个按钮,但是这个 function 没有分配给任何动态按钮。 Kindly help me resolving this.请帮我解决这个问题。 Thank You.谢谢你。

myfunction() is working but myfunction1() has some problem. myfunction()正在工作,但myfunction1()有一些问题。 I cannot see onclick event in its dynamically HTML.我在其动态 HTML 中看不到 onclick 事件。 HTML 视图

There are JS file.有JS文件。 data.js contains arrays of objects and other contains function which access the data. 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,
  }

];

This issue occurred because you defined myfunction1 dynamically.出现此问题是因为您动态定义myfunction1 In other words, this element wasn't defined during the initial rendering of the page.换句话说,这个元素不是在页面的初始渲染过程中定义的。

You can fix it by using event delegation.您可以使用事件委托来修复它。 Here is how:方法如下:

Instead of defining the callback on the element, define it for all children of the PARENT element that have the matching css class.不要在元素上定义回调,而是为PARENT元素的所有具有匹配 css class 的子元素定义它。 For example:例如:

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

    });

where:在哪里:

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

Now when you add buttons with (class name btn ) dynamically as children of btnContainer , they will still get access to the click handler, because the event handler isn't bound to the element btn , but to it's parent , hence when the click event is fired, the parent delegates the event to all it's children with the matching class(es)!现在,当您将带有(类名btn )的按钮动态添加为btnContainer的子级时,它们仍然可以访问单击处理程序,因为事件处理程序未绑定到元素btn ,而是绑定到它的parent ,因此当单击事件被触发时,父级将事件委托给所有具有匹配类的子级!

  1. Do not add a function in a loop不要在循环中添加 function
  2. Delegate代表

Have a look here.看看这里。 There are MANY issues, I have addressed a few of them有很多问题,我已经解决了其中一些

You MAY want to do你可能想做

button.setAttribute("data-code",item.code);

instead of代替

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