如何在javascript中访问动态创建的对象?

时间:2012-10-08 07:49:51

标签: c# javascript asp.net dynamic

我创建了一个动态表,我想在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>

提前谢谢你 /约翰

6 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>

答案 2 :(得分: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>

答案 3 :(得分:0)

在javascript中,像这样

var elem = document.getElementById("button-no-1");

答案 4 :(得分: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>

答案 5 :(得分:0)

您应该知道按钮ID:

var button = document.getElementById("button-no-1");