2

鉴于下面的代码,我怎样才能对其进行修改,以便它会提醒我任何选定行的第一列中的值是什么?

即选定的行是第二个,所以,alert("oranges")

<html>
<head>
<script type="text/javascript">
window.onload = function() {

var x = '<table id="mstrTable" border="1" cellspacing="1" width="100">\n'
      + '<tr><td>Apples</td><td>Carrots</td></tr><tr><td>Oranges</td><td>Celery</td></tr>\n'
      + '</table>\n' 
document.getElementById('test').innerHTML = x
var color = "#E1E0D7"
var rows = document.getElementById("mstrTable").getElementsByTagName("tr");
var n = rows.length;
var bgcs = [];
for(var i=0; i<n; ++i) bgcs[i] = rows[i].style.backgroundColor;

function changeColor(e) {
if(!e) e = window.event;
var o = e.target? e.target: e.srcElement;
while(o.tagName && o.tagName.toLowerCase()!="tr") o = o.parentNode;
    for(var i=0; i<n; ++i) {
    rows[i].style.backgroundColor = bgcs[i];
    if(rows[i]==o) rows[i].style.backgroundColor = color;
    }
}//end of function

if(document.addEventListener) for(var i=0; i<n; ++i) rows[i].addEventListener("click", changeColor, false);
else for(var i=0; i<n; ++i) rows[i].attachEvent("onclick", changeColor);

}//end of onload()
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
4

2 回答 2

0
var rows = document.getElementById("mstrTable").getElementsByTagName("tr");
function getFirstCol(row){
    alert(row.getElementsByTagName('td')[0].innerHTML);
}
// Example usage
getFirstCol(rows[0]);
于 2012-06-22T19:07:48.310 回答
0

tr更改颜色时获取节点的子节点。

if(rows[i]==o) {
    rows[i].style.backgroundColor = color;
    console.log(rows[i].children[0])
}

演示

于 2012-06-22T19:08:41.267 回答