Javascript 在javascript中的另一个元素中获取html元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4932239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get html element inside another element in javascript
提问by Red Swan
Hi I am creating dynamic div elements , let say 4 div are there . div1,div2,div3,div4. each div has set of radio buttons rad1,rad2,rad3,rad4 . see as follows.
嗨,我正在创建动态 div 元素,假设有 4 个 div。div1、div2、div3、div4。每个 div 都有一组单选按钮 rad1,rad2,rad3,rad4 。如下。
div1 ->rad1,rad2,rad3,rad4 groupName=rd1 ->end div1
div2 ->rad1,rad2,rad3,rad4 groupName=rd2 ->end div2
div3 ->rad1,rad2,rad3,rad4 groupName=rd3 ->end div3
div4 ->rad1,rad2,rad3,rad4 groupName=rd4 ->end div4
This is dynamically created html. i want to get which Radio selected from div2 or div3 what script i have to write ?
这是动态创建的 html。我想从 div2 或 div3 中选择哪个 Radio 我必须写什么脚本?
采纳答案by Luca Filosofi
function checkRadio() {
var radios = document.getElementById('rBox').getElementsByTagName('input');
for (var i = 0; i < radios.length; i++) {
radios[i].onclick = function(e) {
var pid = this.parentNode.id;
if ( pid == 'group-2' || pid == 'group-3' )
alert('PARENT: ' + this.parentNode.id )
}
}
}
<body onload="checkRadio()">
<div id="rBox">
<div class="rad" id="group-1">
<input type="radio" name="option" />
....
</div>
<div class="rad" id="group-2">
<input type="radio" name="option" />
....
</div>
....
</div>
</body>
回答by Shrinath
use jquery
use jquery-> $.live()
使用 jquery
使用 jquery-> $.live()
回答by aorcsik
If I understood you right, this may help you:
如果我理解正确,这可能会对您有所帮助:
var num_of_options = 4;
var selected = new Array();
var op, i, j;
for (j=1;j<=num_of_options;j++) {
op = document.getElementsByName("rd"+j);
for (i in op) {
if (op[i].checked) {
selected[j] = op[i].value;
}
}
}
selected
will contain the selected values for the radio groups in each divs.
selected
将包含每个 div 中无线电组的选定值。
回答by Shadow Wizard is Ear For You
Here is crude sample code that will show the selected value in each div
:
这是粗略的示例代码,它将显示每个中的选定值div
:
var arrDivs = ["div1", "div2", "div3"];
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = document.getElementById(arrDivs[i]);
if (oDiv) {
var arrInputs = oDiv.getElementsByTagName("input");
var blnFound = false;
for (var j = 0; j < arrInputs.length; j++) {
var oInput = arrInputs[j];
if (oInput.type == "radio" && oInput.checked) {
alert("The value of selected radio in div '" + arrDivs[i] + "' is: " + oInput.value);
blnFound = true;
break;
}
}
if (!blnFound)
alert("div '" + arrDivs[i] + "' contains no selected radio button");
}
else {
alert("div was not found: " + arrDivs[i]);
}
}