检索所选行中的值

时间:2012-06-22 19:04:30

标签: javascript html dom

鉴于下面的代码,如何修改它以便它会提醒我任何所选行的第一列中的值是什么?

即。选定的行是第二个,因此,警告(“橙子”)

<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>

2 个答案:

答案 0 :(得分:0)

var rows = document.getElementById("mstrTable").getElementsByTagName("tr");
function getFirstCol(row){
    alert(row.getElementsByTagName('td')[0].innerHTML);
}
// Example usage
getFirstCol(rows[0]);

答案 1 :(得分:0)

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

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

DEMO