JavaScript突出显示选定的表行

时间:2014-06-08 05:24:57

标签: javascript html css

基本上我有一个动态创建的表。我想要做的是当选择某一行中的链接时,所选行将以背景颜色突出显示。如果我选择另一行,则将删除先前选定的行背景颜色。这是我的表的JavaScript:

var nameLocate = "";
var allcookies = document.cookie;
// SPLIT ARRAY x1st
cookiearray = allcookies.split(';');
$('#divBookmarkResults').fadeIn();

// Now take key value pair out of this array
var htmlStr = "";
htmlStr = htmlStr + "<p style='font-size:9pt;align:left;margin:5px 0px 0px 15px;'>Below are the list of bookmarks stored:</p>";
htmlStr = htmlStr + "<div id='bookmarkResult' style='width:90%; height:105px;'>";
htmlStr = htmlStr + "<table width='100%' id='bookmarkTable' height='50px' style='margin: 10px 0px 0px 15px; border-collapse: collapse'>";
// for each of the cookies within the array get out the values for name and x/y
for (var i = 0; i < cookiearray.length; i++) {
    var bookmarkPosition = i + 1;
    // SPLIT ARRAY x2nd 
    var locationarray = cookiearray[i].split(':');
    var noCookieID = locationarray[0].split('=');

    cookieIndex = noCookieID[0];
    nameLocate = noCookieID[1];

    xValue = locationarray[1];
    yValue = locationarray[2];

    htmlStr = htmlStr + "<tr class='BookmarkIndex" + bookmarkPosition + "'>";
    htmlStr = htmlStr + "<td><a style='font-family:Arial; font-size:8pt; color:#00CCFF;' href='JavaScript:ZoomTo(" + xValue + "," + yValue + "," + bookmarkPosition + ")'>" + nameLocate + "</a>";
    htmlStr = htmlStr + "<td width='25px' style='padding:0px 0px 0px 5px; margin:0;'><img onclick=\"DeleteBookmarkPlace('bookmarkTable'," + bookmarkPosition + "," + xValue + "," + yValue + ",'" + cookieIndex + "','" + nameLocate + "');\" src='img/recycleBin.png' style='cursor:pointer; width:25px; height: 25px;' /></td>";
    htmlStr = htmlStr + "</td>";
    htmlStr = htmlStr + "</tr>";
}
htmlStr = htmlStr + "</table>";
htmlStr = htmlStr + "</div>";
document.getElementById('divBookmarkResults').innerHTML = htmlStr

我在网上找到了一些解决方案,但似乎没有效果:

<tr onclick="this.style.backgroundColor='red'">

任何指南?

提前致谢。

1 个答案:

答案 0 :(得分:0)

由于您已经提到过您可以在评论中使用jQuery,您可以尝试以下内容:

CSS

.highlighted{
 background:red;
}

脚本

$('#divBookmarkResults').on('click','tr', function(){
 $('.highlighted').removeClass('highlighted');
 $(this).addClass('highlighted');
});

这假设#divBookmarkResults是文档中的静态元素,如果它没有将处理程序绑定到更高级别的静态父级,或者作为最后的手段,则绑定到document本身,这是根元素。 这样做的好处是不必将事件处理程序绑定到每个<tr>。 如果您只想定位正文中的<tr>,可以将选择器更改为tbody tr