gpt4 book ai didi

jquery - jQuery 中的可折叠表格

转载 作者:太空狗 更新时间:2023-10-29 15:27:51 26 4
gpt4 key购买 nike

我正在尝试创建一个表格,其中包含可以使用 jQuery 折叠和展开的标题行。到目前为止,这是我的全部代码:

<html>                                                                  
<head>
<script type="text/javascript" src="jquery.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />


<script type="text/javascript">
$(document).ready(function() {

$("tr#cat1.header").click(function () {
$("tr#cat1.child").each(function() {
$(this).slideToggle("fast");
});
});


});

</script>

</head>
<body>

<table>
<tr id="cat1" class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr id="cat1" class="child">
<td>data1</td>
<td>data2</td>
</tr>
<tr id="cat1" class="child">
<td>data3</td>
<td>data4</td>
</tr>
<tr id="cat2" class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr id="cat2" class="child">
<td>data1</td>
<td>data2</td>
</tr>
</table>

</body>
</html>

如果我是正确的,英文的 jQuery 部分是这样的:“当单击 ID 为‘c​​at1’且类为‘header’的行时,查找所有具有 id 为‘cat1’的行,并且一类“ child ”,对于每个 child ,slideToggle。”

然而,当我运行它并单击标题行时,没有任何反应。有什么见解吗?

编辑:在 HTML 表格中添加了第二个类别。抱歉,我应该更具体一些。我希望能够单击特定类别的标题行,并且仅折叠那些子行,而不是页面上的所有子行。以这种方式,表格的行为就像一个“ Accordion ”,并且行按类别分组在一起。

最佳答案

这将导致点击仅影响包含您点击的标题的表格中的行,这意味着您可以将其更改为使用 css 类而不是复制 id。

$("tr#cat1.header").click(function () { 
$("tr#cat1.child", $(this).parent()).slideToggle("fast");
});

基本上 this 是被点击的标题,我们将其包装在一个 jQuery 对象中并调用 parent()(返回表格),然后将其指定为新查询的上下文。

您的页面现在看起来像这样:

<html>                                                                  
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />


<script type="text/javascript">
$(document).ready(function() {

$("tr.header").click(function () {
$("tr.child", $(this).parent()).slideToggle("fast");
});


});

</script>

</head>
<body>

<table>
<tr class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr class="child">
<td>data1</td>
<td>data2</td>
</tr>
<tr class="child">
<td>data3</td>
<td>data4</td>
</tr>
</table>

<table>
<tr class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr class="child">
<td>data1</td>
<td>data2</td>
</tr>
<tr class="child">
<td>data3</td>
<td>data4</td>
</tr>
</table>
</body>
</html>

关于jquery - jQuery 中的可折叠表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1985647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com