用户单击时尝试突出显示表中的行

时间:2014-04-18 17:20:51

标签: javascript jquery html

我正在尝试从JS Fiddle link复制上面的解决方案,但无法加载它。 我错过了什么?

我正在尝试从此question实施解决方案。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<style>

.table-striped  tr.highlight td { 
    background-color: blue;
    color:white;
}

</style>

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

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});
</script>
</head>

<body>
<table id="mytable" class="table-striped">
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
</table>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您的目标是:

tbody tr

但是你的html中不存在body,所以从jQuery中删除tbody它应该可以工作。

像这样:

$('#mytable').on('click', 'tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});

答案 1 :(得分:1)

由于没有创建DOM,因此没有触发此单击,因此jQuery无法找到绑定click事件的元素。你应该在正文的末尾加载你的javascript或将你的javascript包装在一个窗口onload函数中。 FIDDLE

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<style>

.table-striped  tr.highlight td { 
    background-color: blue;
    color:white;
}

</style>


</head>

<body>
<table id="mytable" class="table-striped">
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
        <tr><td>blah blah blah blah</td></tr>
</table>

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

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});
</script>
</body>
</html>

答案 2 :(得分:1)

你的dom中没有tbody。 使用

$('#mytable').on('click', 'tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});

从点击事件中取消tbody