1

我创建了一个动态表,我想在 javascript 中访问创建的对象之一。例如:如何处理动态创建的按钮?

<script type="text/javascript">
function myJavaScriptFunction()
{ 
 //How do I know here which button triggered the function?
}
</script>

<table>
<% for (var i=0; i<10; i++) { %> 
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction()"/>
   </td>
 </tr>
<% } %>
</table>

提前谢谢你/约翰

4

6 回答 6

1

将按钮元素作为参数传递给函数

<script type="text/javascript">
function myJavaScriptFunction(button)
{ 
 //button triggered the function
}
</script>

<table>
<% for (var i=0; i<10; i++) { %> 
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction(this)"/>
   </td>
 </tr>
<% } %>
</table>
于 2012-10-08T07:52:29.940 回答
1

将参数映射为对象:

function myJavaScriptFunction(object)
{ 
 //How do I know here which button triggered the function?
    var id = object.id;
}

在您的 HTML 中,您需要执行以下操作:

onclick="myJavaScriptFunction(this)"

这是你调用函数的地方,你把this关键字作为参数传入。

关键字this指的是执行调用的任何 HTML 元素,即您单击的任何按钮。该对象具有id您在函数中定义为的属性object.id。属性的值id基本上是输入标签的“id”字段。

把它们放在一起,你会得到:

<script type="text/javascript">
function myJavaScriptFunction(object) // You're defining the function as having a parameter that it accepts. In this case, it accepts an object.
{ 
   alert(object.id); // Alert the object's id.
   // Do what you want with object.id
}
</script>

<table>
<% for (var i=0; i<10; i++) { %> 
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction(this)"/>
   </td>
 </tr>
<% } %>
</table>
于 2012-10-08T07:53:07.450 回答
1
<script type="text/javascript">
function myJavaScriptFunction(button)
{ 
   alert($(button).attr('id')); // gets the id of the button that called the function
}
</script>

<table>
<% for (var i=0; i<10; i++) { %> 
  <tr class="rowcell">
   <td class="datacell">
   <input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction(this)"/>
   </td>
 </tr>
<% } %>
</table>
于 2012-10-08T07:54:52.783 回答
0

在javascript中,像这样

var elem = document.getElementById("button-no-1");
于 2012-10-08T07:52:16.950 回答
0

您可以按如下方式更改代码:

<input type="button" id='<%="button-no-"+i%>' value="myButton" onclick="myJavaScriptFunction('<%="button-no-"+i%>')"/>



<script type="text/javascript">
function myJavaScriptFunction(buttonId)
{ 
 //How do I know here which button triggered the function?
}
</script>
于 2012-10-08T07:52:54.637 回答
0

您应该知道按钮 ID:

var button = document.getElementById("button-no-1");
于 2012-10-08T07:53:30.070 回答