-1

我需要检查表单的所有单选按钮并绘制包含选中的 td 的 td。不能在循环(aca)中传递TD id的变量:

function veamos() {

    var allElems = document.getElementsByTagName('input');

        for (i = 0; i < allElems.length; i++) {

           if (allElems[i].type === 'radio' && allElems[i].checked) {

           var aca="pinta"+i;

                document.getElementById(aca).style.backgroundcolor = '#9e0000';

           } else {
            //document.getElementById(estetd).style.backgroundColor = '#ffffff';
           }        
        }       
}

document.getElementById('pinta1').style.backgroundColor = '#9e0000',似乎有效......无法构建变量以循环所有表单

有任何想法吗?提前致谢。

4

3 回答 3

1

你有一个错字。Javascript 区分大小写。改变

document.getElementById(aca).style.backgroundcolor = '#9e0000';

document.getElementById(aca).style.backgroundColor = '#9e0000';

...

更新查看一个工作示例

于 2012-06-27T23:14:31.023 回答
1

如果我正确理解您的问题,我认为您有两个选择。

function veamos () {
  var allElems = document.getElementsByTagName('input');
  for (var i = 0, len = allElems.length; i<len; i++) { /* do not use .length in the loop condition, that will have very bad performance on element arrays returned by getElementsByTagName. */
    var elem = allElems[i];
    if (elem.type==='radio') {
       /* Option 1: This depends on the HTML structure, where is the TD in relation to the input? */
       var td = elem.parentNode; /* if it is 2 levels up then use elem.parentNode.parentNode */
       /* Option 2: This depends on having an ID on the <input> and <td> that are similar, like this <input id="r1"> <td id="r1TD"> */
       var td = document.getElementById(elem.id + 'TD');
       td.style.backgroundColor = elem.checked ? '#9e0000' : '#ffffff';
       /* I would recommend using a class name (CSS) instead of using a hard coded color! */
    }
  }
}
于 2012-06-27T23:34:18.887 回答
0

反而

document.getElementById(aca).style.backgroundcolor = '#9e0000';

应该

allElems[i].style.backgroundcolor = '#9e0000';
于 2012-06-27T23:14:41.347 回答