简体   繁体   English

如何在表中绑定 onclick 事件?

[英]How can I bind onclick event in table?

I want a click event in the table when I am generating a dynamic table.当我生成动态表时,我希望在表中有一个点击事件。 I tried it like this.我这样试过。

 var cartItem=[{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button Henley placket, The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}}] function getcartDetails() { document.getElementById("cartItemShow").innerHTML = ""; for (var get in cartItem) { var tr = document.createElement("tr"); var tdTitle = document.createElement("td"); var tdImage = document.createElement("td"); var tdDel = document.createElement("td"); var img = document.createElement("img"); var button = document.createElement("button"); // =============================================== img.src = cartItem[get].image; img.width = 70; tdTitle.innerHTML = cartItem[get].title; button.innerText="delete"; //button.span.onclick = "delete()"; i want apply an event //=================================================== tdImage.appendChild(img); tdDel.appendChild(button); tr.appendChild(tdTitle); tr.appendChild(tdImage); tr.appendChild(tdDel); console.log("this is id:" + get); document.getElementById("cartItemShow").appendChild(tr); } } getcartDetails() /*function delete(){ alert("hello") }*/
 <div class="col-md-3"> <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button> <table class="table collapse" id="showTable"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Image</th> <th scope="col">action</th> </tr> </thead> <tbody id="cartItemShow"></tbody> </table> </div>

But I am unable to add on click event.但我无法添加点击事件。 Expected Output: After clicking on the delete button, it should appear an alert message with the string "hello".预期 Output:点击删除按钮后,应该会出现一条带有字符串“hello”的警告信息。

you can accomplish that by adding class to the button element button.setAttribute("class", "delete");您可以通过将 class 添加到按钮元素button.setAttribute("class", "delete"); also i will add data-id attribute to define the id value of clicked delete button in table我还将添加 data-id 属性来定义表中单击的删除按钮的 id 值

button.dataset.id = cartItem[get].id;

and add click event on this class jquery并在此 class jquery 上添加点击事件

$(document).on('click', '.delete', function() {
             alert("delete : " + this.dataset.id)
            });

or using native JS或者使用原生 JS

var elements = document.getElementsByClassName("delete");

var deleteRow = function() {
    alert("delete : " + this.dataset.id)
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', deleteRow, false);
}

your code after edits:编辑后的代码:

    <div class="col-md-3"><div class="col-md-3">
          <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button>
          <table class="table collapse" id="showTable">
            <thead>
              <tr>
                <th scope="col">Title</th>
                <th scope="col">Image</th>
                <th scope="col">action</th>
              </tr>
            </thead>
            <tbody id="cartItemShow"></tbody>
          </table>
        </div>
<script>


var cartItem=[{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}}]
function getcartDetails() {
        document.getElementById("cartItemShow").innerHTML = "";
        for (var get in cartItem) {
          var tr = document.createElement("tr");
          var tdTitle = document.createElement("td");
          var tdImage = document.createElement("td");
          var tdDel = document.createElement("td");
          var img = document.createElement("img");
          var button = document.createElement("button");
          // ===============================================
          img.src = cartItem[get].image;
          img.width = 70;
          tdTitle.innerHTML = cartItem[get].title;
          button.innerText="delete";
          button.setAttribute("class", "delete");
          button.dataset.id = cartItem[get].id;
          
          //button.span.onclick = "delete()"; i want apply an event
          //===================================================
          tdImage.appendChild(img);
          tdDel.appendChild(button);
          tr.appendChild(tdTitle);
          tr.appendChild(tdImage);
          tr.appendChild(tdDel);
          console.log("this is id :" + get);
          document.getElementById("cartItemShow").appendChild(tr);
        }
      }
      getcartDetails()

      $(document).on('click', '.delete', function() {
              alert("delete : " + this.dataset.id)
            });

Set a click eventListener on button :button上设置点击事件监听器:

  button.addEventListener("click", () => {
    alert("Hello, World!");
  });

Full code:完整代码:

 var cartItem=[{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}}] function getcartDetails() { document.getElementById("cartItemShow").innerHTML = ""; for (var get in cartItem) { var tr = document.createElement("tr"); var tdTitle = document.createElement("td"); var tdImage = document.createElement("td"); var tdDel = document.createElement("td"); var img = document.createElement("img"); var button = document.createElement("button"); // =============================================== img.src = cartItem[get].image; img.width = 70; tdTitle.innerHTML = cartItem[get].title; button.innerText="delete"; button.addEventListener("click", () => { alert("Hello, World;"); }). //button.span;onclick = "delete()". i want apply an event //=================================================== tdImage;appendChild(img). tdDel;appendChild(button). tr;appendChild(tdTitle). tr;appendChild(tdImage). tr;appendChild(tdDel). console:log("this is id;" + get). document.getElementById("cartItemShow");appendChild(tr); } } getcartDetails() /*function delete(){ alert("hello") }*/
 <div class="col-md-3"> <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button> <table class="table collapse" id="showTable"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Image</th> <th scope="col">action</th> </tr> </thead> <tbody id="cartItemShow"></tbody> </table> </div>

so, the main reason you get an error is that you are trying to use delete operator as a function.因此,出现错误的主要原因是您尝试将删除运算符用作 function。

First , you have to change the function delete to something else, since delete is an operator in Javascript, in my case, I changed it to deleteMe()首先,您必须将function delete更改为其他内容,因为delete是 Javascript 中的运算符,在我的例子中,我将其更改为deleteMe()

second , is change第二,是变化

//button.span.onclick = "delete()"; i want apply an event

to

button.onclick = function (){deleteMe();} //i want apply an event

the reason I have put that in the anonymous function is that I don't want to be triggered after loading the page.我把它放在匿名 function 中的原因是我不想在加载页面后被触发。

the rest of your code is working well.您的代码的 rest 运行良好。

Javascript Delete operator Javascript 删除操作员

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/jquery-ui.min.css" rel="stylesheet">

    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <title>Stack25</title>
</head>
<body>

<div class="col-md-3">
    <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span
            id="itemCount"></span>] Your cart
    </button>
    <table class="table collapse" id="showTable">
        <thead>
        <tr>
            <th scope="col">Title</th>
            <th scope="col">Image</th>
            <th scope="col">action</th>
        </tr>
        </thead>
        <tbody id="cartItemShow"></tbody>
    </table>
</div>

<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<script>

    var cartItem = [{
        "id": 2,
        "title": "Mens Casual Premium Slim Fit T-Shirts ",
        "price": 22.3,
        "description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
        "category": "men's clothing",
        "image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
        "rating": {"rate": 4.1, "count": 259}
    }]

    function getcartDetails() {
        document.getElementById("cartItemShow").innerHTML = "";
        for (var get in cartItem) {
            var tr = document.createElement("tr");
            var tdTitle = document.createElement("td");
            var tdImage = document.createElement("td");
            var tdDel = document.createElement("td");
            var img = document.createElement("img");
            var button = document.createElement("button");
            // ===============================================
            img.src = cartItem[get].image;
            img.width = 70;
            tdTitle.innerHTML = cartItem[get].title;
            button.innerText = "delete";

            //button.span.onclick = "delete()"; i want apply an event
            button.onclick = function (){deleteMe();} //i want apply an event
            //===================================================
            tdImage.appendChild(img);
            tdDel.appendChild(button);
            tr.appendChild(tdTitle);
            tr.appendChild(tdImage);
            tr.appendChild(tdDel);
            console.log("this is id :" + get);
            document.getElementById("cartItemShow").appendChild(tr);
        }
    }

    getcartDetails();

    function deleteMe(){
        alert("hello");
    }

    // function delete(){
    //     alert("hello");
    // }

</script>


</body>
</html>

A couple of things to keep in mind.有几件事要记住。

  • delete is a reserved keyword. delete是保留关键字。 So you have to rename your function. Give it a name so that you instantly know what it does and what is being deleted.所以你必须重命名你的 function。给它一个名字,这样你就可以立即知道它做了什么以及正在删除什么。
  • Looping over arrays should be done with for , forEach or for...of .循环遍历 arrays 应该使用forforEachfor...of来完成。 for...in is used to loop over objects. for...in用于遍历对象。 See this thread to understand the difference between for...of and for...in .请参阅此线程以了解for...offor...in之间的区别。

I'm assuming that you want to know which button is clicked.我假设您想知道单击了哪个按钮。 Therefor set value of the button equal to the id of the cartItem .因此,将buttonvalue设置为等于cartItemid This way you can get the id from the clicked button.这样你就可以从点击的按钮中获取id

You could add an event listener for every button, but it's better (more performant) to use event delegation .您可以为每个按钮添加一个事件侦听器,但使用事件委托会更好(性能更高)。 This is a method of using a single event listener to capture the events of the children.这是一种使用单个事件侦听器来捕获子项事件的方法。 In this case you'd a single click event listener to an element high up the DOM and uncover which element has been clicked.在这种情况下,您需要一个单击事件侦听器来侦听 DOM 上方的元素并发现哪个元素已被单击。 If one of our buttons is clicked, then execute the deleteCartItem function.如果我们的其中一个按钮被点击,那么执行deleteCartItem function。

 var cartItems = [{ "id": 2, "title": "Mens Casual Premium Slim Fit T-Shirts ", "price": 22.3, "description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.", "category": "men's clothing", "image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg", "rating": { "rate": 4.1, "count": 259 } }]; // Delete cart item with id. function deleteCartItem(id) { alert(`Delete item id: ${id}`); } // Listen for all delete button clicks. document.addEventListener('click', ({ target }) => { console.log(target); if (target.tagName === 'BUTTON' && target.classList.contains('delete-cart-item')) { deleteCartItem(target.value); } }); function getcartDetails() { document.getElementById("cartItemShow").innerHTML = ""; for (const cartItem of cartItems) { var tr = document.createElement("tr"); var tdTitle = document.createElement("td"); var tdImage = document.createElement("td"); var tdDel = document.createElement("td"); var img = document.createElement("img"); var button = document.createElement("button"); // =============================================== img.src = cartItem.image; img.width = 70; tdTitle.innerHTML = cartItem.title; button.value = cartItem.id; button.className = 'delete-cart-item'; button.innerText = "delete"; //=================================================== tdImage.appendChild(img); tdDel.appendChild(button); tr.appendChild(tdTitle); tr.appendChild(tdImage); tr.appendChild(tdDel); console.log("this is id:" + cartItem.id); document.getElementById("cartItemShow").appendChild(tr); } } getcartDetails()
 <div class="col-md-3"> <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button> <table class="table collapse" id="showTable"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Image</th> <th scope="col">action</th> </tr> </thead> <tbody id="cartItemShow"></tbody> </table> </div>

Use event delegation .使用事件委托 Instead of attaching listeners to every button add one listener to the parent element (in this case the tbody element), and have that capture all the events from its child elements as they "bubble up" the DOM, and have that listener call a function to update the table.不是将侦听器附加到每个按钮,而是将一个侦听器添加到父元素(在本例中为tbody元素),并在它们“冒泡” DOM 时从其子元素捕获所有事件,并让该侦听器调用 function更新表格。

I've used a slightly more modern approach to building the rows in my answer that you may find useful.我在我的答案中使用了一种稍微更现代的方法来构建您可能会觉得有用的行。 Links to all the relevant MDN documentation are at the end of the answer.所有相关 MDN 文档的链接都在答案的末尾。

 const data = [{"id":1,"title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops","price":109.95,"description":"Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday","category":"men's clothing","image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg","rating":{"rate":3.9,"count":120}},{"id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}},{"id":3,"title":"Mens Cotton Jacket","price":55.99,"description":"great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.","category":"men's clothing","image":"https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg","rating":{"rate":4.7,"count":500}},{"id":4,"title":"Mens Casual Slim Fit","price":15.99,"description":"The color could be slightly different between on the screen and in practice. / Please note that body builds vary by person, therefore, detailed size information should be reviewed below on the product description.","category":"men's clothing","image":"https://fakestoreapi.com/img/71YXzeOuslL._AC_UY879_.jpg","rating":{"rate":2.1,"count":430}},{"id":5,"title":"John Hardy Women's Legends Naga Gold & Silver Dragon Station Chain Bracelet","price":695,"description":"From our Legends Collection, the Naga was inspired by the mythical water dragon that protects the ocean's pearl. Wear facing inward to be bestowed with love and abundance, or outward for protection.","category":"jewelery","image":"https://fakestoreapi.com/img/71pWzhdJNwL._AC_UL640_QL65_ML3_.jpg","rating":{"rate":4.6,"count":400}}]; // Get the `tbody` element const cartItemShow = document.getElementById('cartItemShow'); // Add an event listener to it. It watches out for all the // events that bubble up from its child elements cartItemShow.addEventListener('click', handleClick, false); // This function checks to see if the element that // was clicked on was the delete button. If it was // it gets the id from the button's dataset, and uses // that to create a selector which cartItemShow can use // to remove a row with the same id function handleClick(e) { if (e.target.matches('.delete')) { const { id } = e.target.dataset; const selector = `tr[data-id="${id}"]`; cartItemShow.querySelector(selector).remove(); } } function buildRows(data) { // `map` over the array, and for each item... const html = data.map(item => { // Destructure the id, title, and image // from the item object const { id, title, image } = item; // Then return some HTML in the form of a // template literal/string. It looks neater // than creating lots of DOM elements, and is // easier to understand. I'm adding the id to both // the row element as well as the button. When the // button is clicked the `handleClick` function // will be called, and the row with the same id // will be removed from the table return ` <tr data-id=${id}> <td>${title}</td> <td><img src="${image}" /></td> <td> <button data-id=${id} type="button" class="delete" > Delete </button> </td> </tr> `; // Make sure you `join` up the array // that `map` returns at the end of the iteration }).join(''); // Add the HTML string to the table body cartItemShow.insertAdjacentHTML('beforeend', html); } buildRows(data);
 img { width: 100px; height: 100px } td { width: 33%; text-align: center; }.delete:hover { cursor: pointer; background-color: #fffff0; }
 <div class="col-md-3"> <button class="btn btn-danger w-100" data-bs-toggle="collapse" data-bs-target="#showTable">[<span id="itemCount"></span>] Your cart</button> <table class="table collapse" id="showTable"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Image</th> <th scope="col">action</th> </tr> </thead> <tbody id="cartItemShow"></tbody> </table> </div>

Additional documentation附加文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM