jQuery单击并显示元素列表

jQuery click and show list of elements

本文关键字:元素 列表 显示 单击 jQuery      更新时间:2023-09-26

我有来自DB的元素列表,并用按钮显示在表中:

<a href="#" class="hiden"></a> 

用于显示和隐藏中包含的预先信息

<div class="object></div>

我的jQuery脚本是:

$(document).ready(function() {
    $(".object").hide();
    $('.hiden').click(function() {
        $(".object").toggle();
    });
});

HTML:

<table class="table table-hover">
<thead>
<tr>
    <th></th>
    <th></th>
    <th></th>
    <th class="but" colspan="2"></th>
</tr>
</thead>
<tbody>
<?php foreach($model as $object): ?>
    <tr>
        <td><a href="#"><?php echo $object->name; ?></a></td>
        <td></td>
        <td></td>
        <td class="but">
        <a href="#" class="hiden"></a> 
        </td>
    </tr>
    <tr>
        <td colspan="4">
            <div class="object">            
                <table class="table table-bordered">
                </table>
            </div>
        </td>
    </tr>
<?php endforeach; ?>
</tbody>
</table>

当点击.hide时,我遇到了一些问题。列表中的所有元素都显示,然后点击所有元素都隐藏。我想要一个元素显示另一个元素隐藏。

请帮助我

$(document).ready(function() {
    $(".object").hide();
    $('.hiden').click(function() {
        $(this).parents('tr').next().find(".object").toggle();
    });
});

Toogle是正确的方法,但如果您点击它们并触发事件,则每个元素都必须有一个唯一的标识符。

更改:

$(".object").toggle();

至:

$(this).closest('tr').next().find(".object").toggle();

您描述的行为就是您实际编码的行为。您的选择器

$(".object").toggle()

切换类为.object的所有元素,而不仅仅是一个。要只切换同一表格行中的一个,您可以

$('.hiden').click(function() {
    $(this).parent("tr").next().find(".object").toggle();
});