简体   繁体   English

无法将变量作为onClick函数中的参数传递

[英]Can't pass a variable as an argument in a onClick function

I want to have a table and its cells are filled with data from MySQL. 我想要一个表,它的单元格充满了MySQL的数据。

The table have many TDs, which have an Id. 该表有许多TD,其中有一个ID。

I want to pass the id of the cell to a function, so that I can edit its content: 我想将单元格的ID传递给函数,以便编辑其内容:

document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList(&quot;Cell_ID&quot;)" value="Edit Action" />';

function SaveUpdateToActionList(Cell) {
    alert(Cell);   
    document.getElementById(Cell).innerHTML = 'Here'; 
}

When I have alert(Cell); 当我有alert(Cell); displayed, I see this sends the Text "Cell_ID", whereas I wanted to see the data ActionButton386 there. 显示,我看到这发送文本“ Cell_ID”,而我想在那里查看数据ActionButton386。

Any help appreciated. 任何帮助表示赞赏。

You can pass in the element being clicked by setting your onClick script to SaveUpdateToActionList(this); 您可以通过将onClick脚本设置为SaveUpdateToActionList(this);来传递被单击的元素SaveUpdateToActionList(this);

Then, in the body of SaveUpdateToActionList , Cell will refer to the button that just got clicked. 然后,在SaveUpdateToActionList的正文中, Cell将引用刚刚单击的按钮。 You can then walk up the DOM to get to the TD it belongs to. 然后,您可以沿DOM走到它所属的TD。

You can try this: 您可以尝试以下方法:

   document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name =      "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList()" value="Edit Action" />';

   function SaveUpdateToActionList(event) {
    alert(event.target.id);   
    document.getElementById(Cell).innerHTML = 'Here'; 
   }

But if i understand correctly what you are trying to do, you shoud have a single event listner that catches bubling events from all cells, rather that attaching a an onclick to each cell.... 但是,如果我正确理解了您要做什么,您应该拥有一个事件列表器,它可以捕获来自所有单元格的冒泡事件,而不是在每个单元格上附加onclick。

Just register the event listener separately from specifying the innerHTML property: 只需与指定innerHTML属性分开注册事件侦听器:

Document.getElementById(IndexedActionButton).addEventListener('onclick', SaveUpdateToActionList);

SaveUpdateToActionList will be called with an event object as the first argument. 将以事件对象作为第一个参数调用SaveUpdateToActionList You can access which element was clicked by checking the event.target property. 您可以通过检查event.target属性来访问单击了哪个元素。 For more information check out MDN - addEventListener documentation 有关更多信息,请查看MDN-addEventListener文档

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

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