2014-05-17 56 views
0

我想突出显示最后一个项目点击的行。尝试了一些在搜索中发现的jQuery代码,它们甚至都没有尝试工作。必须做一些基本的错误。这里有一个解决方案的jsfiddle尝试:http://jsfiddle.net/birchy/he9ts/1/更改表格行的背景颜色点击

<table> 
<tr> 
<td>====></td> 
<td class='msgRow' onclick='loadMsg();'>Content1</td> 
</tr> 
<tr> 
<td>====></td> 
<td class='msgRow' onclick='loadMsg();'>Content2</td> 
</tr> 
<tr> 
<td>====></td> 
<td class='msgRow' onclick='loadMsg();'>Content3</td> 
</tr> 
<tr> 
<td>====></td> 
<td class='msgRow' onclick='loadMsg();'>Content4</td> 
</tr> 
</table> 

function loadMsg() 
{ 
alert('row clicked'); 
$(this).closest("tr").css('background-color','green'); 
$(this).css('background-color','red'); 
} 
+0

既然你正在使用jQu已经不应该使用'onclick'属性,而是首先通过jQuery将事件处理程序绑定到元素。 – CBroe

+0

检查控制台“this”是否与您点击的内容相关。它提到了窗口。我建议你使用Firebug,并在将来检查类似的东西。 – Skizo

+0

我从未弄清楚萤火虫控制台的工作原理,也没有找到任何有用的网上教程。当我打开萤火虫并点击“控制台”,然后点击表格行,我在列表中获得的所有POST信息都与在js函数中作为bg颜色更改逻辑的ajax调用相关联。如果我查看“控制台”下拉菜单中的选项,它只会提示显示js错误和警告。我不知道我如何看待这个对象。 – birchy

回答

1

试试这个

首先,通过元素的功能点击使用this

<tr> 
    <td>===></td> 
    <td class="msgRow" onclick="onclick(this)">Content 3</td> 
</tr> 

然后在你的js

function loadMsg(e){ 
    // remove first the background applied on all tr 
    $('.msgRow').closest('tr').css('background-color','none'); 

    // remove also the background applied on all 'msgRow' classes 
    $('.msgRow').css('background-color','none'); 

    // then you can now change the background color of the clicked row and cell 
    $(e).closest('tr').css('background-color','green'); 
    $(e).css('background-color','red'); 
} 

DEMO

+0

”,而代码在jsfiddle中完美运行,只有高亮代码在我的实时页面上工作,清除以前高亮行的代码不会“吨,他们仍然强调。除了我不强调td和tr,仅仅是tr之外,我找不到任何重要的区别。 ('。')。css('background-color','none');' '$('。msgRow')。css('background-color','none');' ' '';' ''(e).closest(“tr”).css('background-color','#CCD9DC');' – birchy

+0

我可以这样离开它,以显示所有点击行,但我想确定他们为什么不清楚。 – birchy

+0

超时上编辑的第一个评论,所以这里有一个更好的版本的代码: '' '函数loadMsg( ('。');' '$('。msgRow')。closest('tr')。 css('background-color','none');' '$(e).closest(“tr”)。css('background-color','#CCD9DC');' '}' – birchy

2

只有你需要的是对的onclick这个消息传给其他每个td得到至极TD已被点击:

<tr> 
    <td>====></td> 
    <td class='msgRow' onclick='loadMsg(this);'>Content3</td> 
</tr> 

你的js会:

function loadMsg(e) 
{ 
    alert(e); 
    $(e).closest("tr").css('background-color','green'); 
    $(e).css('background-color','red'); 
} 

Live Demo

另一种方法只jQuery的(Recomended):

$(document).ready(function(){ 
    $('.msgRow').on('click', function(){ 
     $(this).closest("tr").css('background-color','green'); 
     $(this).css('background-color','red'); 
    }); 
}); 

并移除所有td的onclik。