<分区>
标签 c# javascript jquery html css
<分区>
如何为动态创建的文本框和div设置随机id。我必须为动态创建的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>
最佳答案
<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,使其独一无二。
关于c# - 如何为动态创建的文本框和 div 设置随机 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618442/