如何为动态创建的文本框和div设置随机ID

时间:2014-09-02 07:52:26

标签: c# javascript jquery html css

如何为动态创建的文本框设置随机ID,div.i必须为动态创建的div和textbox设置不同的id。请为随机提供id

我的代码在这里

<!DOCTYPE html>


 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head id="Head1" runat="server">
<title>Untitled Page</title>
 <script type="text/javascript">
 function GetDynamicTextBox(value) {
     return '<input name = "DynamicTextBox" type="text"   />' +
             '<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
 }
 function AddTextBox() {
     var div = document.createElement('DIV');
     div.innerHTML = GetDynamicTextBox("");
     document.getElementById("TextBoxContainer").appendChild(div);
 }

 function RemoveTextBox(div) {
     document.getElementById("TextBoxContainer").removeChild(div.parentNode);
 }


</script>

 </head>
 <body>
  <form id="Form2" runat="server">
  <input id="btnAdd" type="button" value="Add Text" onclick="AddTextBox()" />
  <br />
  <br />
  <div id="TextBoxContainer">

  </div>

 </form>

   

2 个答案:

答案 0 :(得分:1)

<script type="text/javascript">

 var randomId = 0;

 function GetDynamicTextBox(value) {
    var newRandomIdOfTextBox = "dynamicTextBox" + randomId++ + "";
     return '<input name = "DynamicTextBox" type="text" id="' + newRandomIdOfTextBox  +'"  />' +
             '<input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
 }
 function AddTextBox() {
     var div = document.createElement('DIV');
     div.innerHTML = GetDynamicTextBox("");
     document.getElementById("TextBoxContainer").appendChild(div);
 }

 function RemoveTextBox(div) {
     document.getElementById("TextBoxContainer").removeChild(div.parentNode);
 }

</script>

randomId从0开始,每次添加新文本框时,它都会增加1,使其唯一..

答案 1 :(得分:0)

你可以设置id =&#34;&#39; sometext&#39; + Math.random();&#34;

如果有帮助,请告诉我