js Table表格选中一行变色或者多选 并获取值

1、原始样式:

 2、鼠标滑过时:

 3、鼠标选中点击某一行

1、先写html语言,当然还是应用的前几天相同的代码,可是多了一点点...

 <div id="testDiv" style=" 60%;margin-left: 10%;margin-top: 50px;height: 1100px;background-color: #f2f2f2;padding: 60px 10px 10px 200px;">
          <table width="100%" height="100px" border="1px"  id="tad" onmouseover="getrow(this)" onmouseout="backrow(this)" onclick="selectRow(this)">
              <tr><td>1</td><td>1</td></tr>
              <tr><td>3</td><td>1</td></tr>
              <tr><td>5</td><td>1</td></tr>
          </table> 
          <input type="button" onclick="b()" value="add">
          <input type="button" onclick="c()" value="delRow">
          <input type="button" onclick="d()" value="delCol">
      </div>

看出区别在哪了么,对就是在table上多了onclick、onmouseover和onmouseout等事件,并且事件传递的參数时table对象本身

2、javascript实现对应的效果

function getrow(obj){
   if(event.srcElement.tagName=="TD"){
   curRow=event.srcElement.parentElement;
   curRow.style.background="yellow";
   }
}
function backrow(obj){
    if(event.srcElement.tagName=="TD"){
    curRow=event.srcElement.parentElement;
    curRow.style.background="#f2f2f2";
    }
}
function selectRow(obj){
    if(event.srcElement.tagName=="TD"){
    curRow=event.srcElement.parentElement;
    curRow.style.background="blue";
    alert("这是第"+(curRow.rowIndex+1)+"");
    }
}

这里的编码有一个最关键点:

event.srcElement.tagName和event.srcElement.parentElement在这里的应用;

event是触发时间的源对象,而srcElement则就是选中对象,而parentElement则是选中对象的父层对象;以当前的样例来简单解释的话,就是说,鼠标放上table,从而激活了时间getrow(this),当鼠标放在任一单元格之上时,它的srcElement都是 td,并且它的parentElement也就是tr一行了,则找到一行的对象了,对它的操作就回到最主要的那些開始了啊

多选的话改动一些就行

function selectRow(obj) {
            if (event.srcElement.tagName == "TD") {
                curRow = event.srcElement.parentElement;
                if (curRow.style.background == "blue") {
                    curRow.style.background = "#f9f9f9";
                }
                else {
                    curRow.style.background = "blue";
                }
            }
        }
delte: function () {
                if (confirm("你确定要删除吗?")) {
                    var index = 1;
                    $('#lsvbody tr').each(function (i, r) {
                        if (r.style.background == "blue") {
                            index = 0;
                            $(this).remove();
//根据条件删除数组的的对象
for (var i = 0; i < lsvData.length; i++) { if (lsvData[i].id == r.id) { lsvData.splice(i, 1); } } } }); if (index==1) { alert("请选择一行!"); } } },
原文地址:https://www.cnblogs.com/netlock/p/13232357.html