2

我有一个需要动态生成字段的表单,并且这些字段具有调用它们的各种 jquery 函数。基本上,我使用 slideUp 和 slideDown 来根据用户选择的内容显示不同的选项。考虑以下代码

    <div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red; margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

<div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red;margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

和jQuery

$('.green').hide();

        $('.red').click(function(){
            $('.green').show();
            });

基本上我只想显示红色之后的绿色框。虽然这个例子很简单,我可以复制我的代码并给第二个项目一个不同的 id,但我的真实形式要复杂得多,所以我想做的是找到一种在每个“测试”div 中按类名定位项目的方法.

4

4 回答 4

3

我想做的是找到一种在每个“测试” div 中按类名定位项目的方法。

很简单:

$('.red').click(function(){
    $(this).closest('.test').find('.green').show();
});
于 2013-07-05T17:00:08.307 回答
2

您可以使用 next() 方法:

$('.red').click(function () {
    $(this).next('.green').show();
});
于 2013-07-05T17:00:19.213 回答
2

两个答案都很好,我只是添加另一个选项:

$('.red').click(function () {
    $(this).siblings('.green').show();
});

Jquery 文档:http ://api.jquery.com/siblings/

于 2013-07-05T17:04:18.103 回答
1

改变

$('.green').show();

$(this).parent('.test').children('.green').show();
于 2013-07-05T17:06:19.970 回答