我的代码如下
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Accordion - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#accordion").accordion();
});
var i = 1;
function pressMe() {
var h3 = document.createElement("h3"),
div = document.createElement("div");
h3.appendChild(document.createTextNode('Section 4'));
div.appendChild(document.createTextNode('Saurabh'));
// note the reverse order of adding child
h3.appendChild(div);
//document.getElementById('accordion').appendChild(h3);
//$( "#accordion" ).accordion();
$("#accordion").append('<h3>Section ' + ++i + '</h3> <div id=\'myDiv' + i + '\'>' + document.getElementById('temp').innerHTML + '</div>');
$("#accordion").accordion("refresh");
}
function hide() {
document.getElementById('temp').style.display = "none";
}
function printAll() {
for (temp = 2; temp <= i; temp++) {
alert(document.getElementById('myDiv' + temp).getElementsByTagName('input')[0].value);
}
}
</script>
</head>
<body id="XXX" onload="hide()">
<div id="accordion">
<h3>Section 1</h3>
<div id='myDiv1'>
<input type="text" name="text1" id="text1">
</div>
</div>
<input type="button" onclick="pressMe()" value="Add more Nodes">
<input type="button" onclick="printAll()" value="printAll">
<div>
<div id='temp'>
<input type="text" name="text1" id="id_text">
</div>
</div>
</body>
我想要做的就是我想要唯一地标识所有输入标签而不是
document.getElementById('myDiv' + temp).getElementsByTagName('input')[0].value
但使用
document.getElementById('myDiv' + temp).getElementsById('id_text')[0].value
但无法追溯该元素。
答案 0 :(得分:0)
document.getElementById('myDiv' + temp)
返回一个HTMLElement
,其原型中有getElementsByTagName
个方法(HTMLElement.prototype.getElementsByTagName
)并且没有getElementsById
方法。
但它有querySelector
方法。您可以像这样使用它:
document.getElementById('myDiv' + temp).querySelector('#id_text').value
答案 1 :(得分:0)
如果您想获取元素输入的所有ID和值,请尝试以下操作:
<强> HTML:强>
<div id="accordion">
<h3>Section 1</h3>
<div id='myDiv1'>
<input type="text" name="text1" id="text1" value="a">
<input type="text" name="text1" id="text2" value="b">
<input type="text" name="text1" id="text3" value="c">
</div>
</div>
<input type="button" onclick="pressMe()" value="Add more Nodes">
<input type="button" onclick="printAll()" value="printAll">
<div>
<div id='temp'>
<input type="text" name="text1" id="id_text">
</div>
</div>
<强> jQuery的:强>
$(document).ready(function(){
var temp = 1;
var IDs = [];
var Values = [];
var Elements = [];
$("#myDiv" + temp).find("input").each(function(){
IDs.push(this.id); // for ID
Values.push($(this).val()); // for Value
Elements.push(this); // for html tags
});
alert(IDs);
});