从特定tr获取td值(鼠标悬停)

时间:2013-11-13 15:12:24

标签: javascript html html-table

我的问题是js可排序表,我也使用鼠标悬停。 问题是,当我使用我的表时,悬停网址没有更新,我正在寻找我如何获得特定的tr我选择了第一个td的值。

我尝试了不同的变体,例如:

$this.find('td:eq(0)') 

getElementById("trselect")

无效。

我在鼠标悬停时都使用它,可能会寻找类似的东西:

document.location.href = "details/" + $('tr').find('td:first-child').text();

3 个答案:

答案 0 :(得分:4)

纯JavaScript解决方案

有一堆jQuery答案,但没有jQuery标签,所以我为你提供了一个纯JavaScript解决方案。为这个简单的任务安装一个大型库似乎毫无意义。

您可以将行分配给这样的Javascript变量,并查找鼠标悬停。

要获得第一个TD的内容,您可以使用如下函数:

function getFirstTdContent(row) {
    elem = row.children[0];
    alert(elem.textContent); // Do whatever you want to do with the content here
}

要调用它,请按以下方式声明您的行:

<tr onmouseover='getFirstTdContent(this);'>
    <td>This should be returned</td>
    <td>This should not be returned</td>
</tr>

答案 1 :(得分:3)

使用jQuery尝试类似的东西:

添加jQuery库:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

添加jQuery代码以获取第一个TD的值:

<script>
$(document).ready(function(){
    $('tr').mouseover(function(){
        var valueOfTd = $(this).find('td:first-child').text();
        alert(valueOfTd); // Do here what you want with the value.
        document.location.href = 'http://www.google.com/'+ valueOfTd;
    });
});
</script>

答案 2 :(得分:1)

看起来你正在使用jQuery ......

试试这个:

http://jsfiddle.net/cF63Q/

$(function(){
    $('#myTable tr').hover(function(){
       console.log($(this).find('td').first().html());
    });
});