简体   繁体   English

如何使用页面上的许多元素动态触发 onclick?

[英]How to trigger onclick dynamically with many elements on the page?

I have few values retrieved from DB.我从数据库中检索到的值很少。 I need to update the product information using one on click function.我需要使用一次单击更新产品信息 function。 Every click only the first product information is being populated.每次点击只会填充第一个产品信息。 I want to load dynamically.我想动态加载。 Can I do it with onclick function?我可以用 onclick function 做吗? please help me.请帮我。

    <tr>
<td id="product_name">Cheese</td>
<td id="product_id">12547777</td>
<td id="scheduled_time">04:00 PM</td>
<td id="distributor_name">Elle Nutrients</td>
<td id="order_status">Complete</td>
<td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this.id)"></i></td>
</tr>
<tr>
<td id="product_name">Butter</td>
<td id="product_id">12577788</td>
<td id="scheduled_time">05:00 PM</td>
<td id="distributor_name">Oetker</td>
<td id="order_status">Waiting</td>
<td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this.id)"></i></td>
</tr>

My script:我的脚本:

function addproduct(){

    var productname = this.$("#product_name").text();
    var productid = this.$("#product_id").text();
    var name = document.getElementById('new_productname');
    name.value = productname;
    var newid = document.getElementById('new_productid');
    newid.value = productid;
}

First, you're passing an argument to the function, but you don't have a parameter in the function definition.首先,您将参数传递给 function,但 function 定义中没有参数。

Second, your syntax for DOM navigation is all wrong.其次,您的 DOM 导航语法完全错误。 Use methods like .closest() and .find() to navigate.使用.closest().find()等方法进行导航。

Third, IDs have to be unique.第三,ID 必须是唯一的。 Use classes for repeated elements.对重复元素使用类。

 function addproduct(element) { var row = $(element).closest("tr"); var productname = row.find(".product_name").text(); var productid = row.find(".product_id").text(); $("#new_productname").val(productname); $("#new_productid").val(productid); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="product_name">Cheese</td> <td class="product_id">12547777</td> <td class="scheduled_time">04:00 PM</td> <td class="distributor_name">Elle Nutrients</td> <td class="order_status">Complete</td> <td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this)">X</i></td> </tr> <tr> <td class="product_name">Butter</td> <td class="product_id">12577788</td> <td class="scheduled_time">05:00 PM</td> <td class="distributor_name">Oetker</td> <td class="order_status">Waiting</td> <td><i class="icon text-info fa fa-pencil" style="cursor: pointer;" onclick="addproduct(this)">X</i></td> </tr> </table> New name: <input id="new_productname"> <br> New ID: <input id="new_productid">

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

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