【问题标题】:how to apply actions to only one instance of a class如何仅将操作应用于类的一个实例
【发布时间】:2013-07-03 20:12:09
【问题描述】:

我有一个需要动态生成字段的表单,并且这些字段具有调用它们的各种 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 中按类名定位项目的方法.

【问题讨论】:

标签: jquery targeting


【解决方案1】:

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

足够简单:

$('.red').click(function(){
    $(this).closest('.test').find('.green').show();
});

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我选择了这个答案,因为我发现它是最容易使用的,但也尝试了其他答案,发现它们也都很出色。谢谢你
    【解决方案3】:

    你可以使用 next() 方法:

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

    【讨论】:

    • 如果我以 dom 顺序中红色之前出现的东西为目标,这仍然有效吗?
    • 所以,使用最接近() 和 find() 但这与您的开场问题不再相关
    【解决方案4】:

    改变

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

    $(this).parent('.test').children('.green').show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2016-10-15
      • 2018-07-16
      • 2017-01-24
      相关资源
      最近更新 更多