我的Html如下所示:
<div id="associatedAPListTable" style="float:left"><Associated (Destination)>
<table border="0" cellspacing="0" cellpadding="0" class="listContainer" align="center" >
<thead>
<tr>
<th class="tableheader" align="left" width="170">MAC address</th>
<th class="tableheader" align="left" width="170">LradName</th>
</tr>
</thead>
<tbody id="associated_tablebody">
</tbody>
</table>
</div>
我的javascript如下所示:
function getAssociatedList(){
var associatedAPListArray=[];
var xhrArgs = {
url:"abc/sample/resource",
preventCache: true,
contentType: "application/json"
};
var deferred = dojo.xhrGet(xhrArgs);
deferred.addCallback(function(response){
var associatedApListObj = dojo.fromJson(response);
var firstJsonObject;
var row = '';
for (i=0; i <= dojo.fromJson(associatedApListObj.items).length-1; i++){
firstJsonObject = dojo.fromJson(associatedApListObj.items)[i];
var MacAddress = firstJsonObject.MacAddress;
var LradName=firstJsonObject.LradName;
var style_td='<td align="left" width="170">';
row+='<tr>'+style_td+'<input type="radio"'+'id="associated_'+i+'" name="associatedAp"/ >'+MacAddress+'</td>'+style_td+LradName+'</td></tr>';
}
document.getElementById('associated_tablebody').innerHTML = row;
});
}
所以,现在我已经创建并显示了这些单选按钮, 我需要选择单选按钮的值。有人可以告诉我如何做到这一点是Javascript而不是jQuery?
答案 0 :(得分:0)
这将为您提供已检查单选按钮的id
:
document.querySelector('input[type=radio]:checked').getAttribute('id');
答案 1 :(得分:0)
如果您希望收听用户事件,则需要在创建元素后为其添加事件侦听器。
function handleChange(e) {
// is it checked?
console.log(this.checked)
// what's the value?
console.log(this.value)
}
var inputs = document.getElementById('associated_tablebody').querySelectorAll('input')
inputs.forEach(function(el) {
el.addEventListener('change', handleChange)
})
更新
我以为你想听每个输入的事件。我的坏。
如果您只是想在将html添加到页面后找到所选的单个单选按钮,只需将结果过滤到所选元素并存储(或记录)它的值:
var inputs = document.getElementById('associated_tablebody').querySelectorAll('input')
var selected = [].slice.call(inputs).filter(function(el) {
return el.checked
}).pop()
console.log(selected.value)
答案 2 :(得分:0)
首先,我猜你想要所选单选按钮的Mac地址吗?
根据您的代码,由于您说
,因此不清楚我需要选择单选按钮的值
然而,您正在生成此输入标记
<input type="radio"'+'id="associated_'+i+'" name="associatedAp"/ >
没有设置值,否则它可能如下所示:
<input type="radio"'+'id="associated_'+i+'" name="associatedAp" value="'+MacAddress+'"/ >
要清楚整行代码如下:
row+='<tr>'+style_td+'<input type="radio"'+'id="associated_'+i+'" name="associatedAp" value="'+MacAddress+'" />'+MacAddress+'</td>'+style_td+LradName+'</td></tr>';
现在您需要能够选择它并获得值:
var selection = document.querySelector('input:checked').value;