javascript - jquery:运行脚本而不影响具有相同类的 div

标签 javascript jquery html css

有一个产品循环,我需要在点击时更改图像。就像在每个产品循环中一样,有一大堆具有相同类的 div。就我而言,这会受到影响。不能孤立他们。初始图像确实消失了。但不是一个,这是有意的,而是所有的。并且没有新图像出现

单品html

<div class="product">
    <div class="galwrap displaytable">
        <div class=" galitem galitem1"></div>
        <div class=" galitem galitem2"></div>
    </div>
    <div class="displaytable galcolors">
        <div class="displaytablecell galcolor galcolor1"></div>
        <div class="displaytablecell galcolor galcolor2"></div>
    </div>
</div>

和jquery

$(".product").each(function () {
    $(this).find(".galcolor2").click(function () {
        $(".galitem").hide();
        $(this).parent().find(".galitem2").show();
    });
});

http://jsfiddle.net/h1twaf1y/

最佳答案

http://jsfiddle.net/q72nw00t/2/

Javascript:

$(".galcolor2").click(function(){
    $(".galitem").hide();
    $(this).parent().parent().find(".galitem2").show();
});

HTML:(这只是一遍又一遍重复的部分)

<div class="product">
<div class="galwrap displaytable">
 <div class=" galitem galitem1">this will be hidden</div>
 <div class=" galitem galitem2" style="display: none">this will be shown</div>
</div>   
<div class="displaytable galcolors">
 <div class="displaytablecell galcolor galcolor1"></div>
 <div class="displaytablecell galcolor galcolor2">click this</div>
</div>
</div>
----------
<div class="product">
<div class="galwrap displaytable">
 <div class=" galitem galitem1">this will be hidden</div>
 <div class=" galitem galitem2" style="display: none">this will be shown</div>
</div>   
<div class="displaytable galcolors">
 <div class="displaytablecell galcolor galcolor1"></div>
 <div class="displaytablecell galcolor galcolor2">click this</div>
</div>
</div>
----------
<div class="product">
<div class="galwrap displaytable">
 <div class=" galitem galitem1">this will be hidden</div>
 <div class=" galitem galitem2" style="display: none">this will be shown</div>
</div>   
<div class="displaytable galcolors">
 <div class="displaytablecell galcolor galcolor1"></div>
 <div class="displaytablecell galcolor galcolor2">click this</div>
</div>
</div>

基本上您想要监听所有 .galcolor2 上的任何点击,然后在点击时隐藏所有 .galitem,然后通过向上两级到 div.product 并找到正确的元素只显示相关的 .galitem2

您初始代码中的问题是,您使用 parent() 仅上升了一个级别到 div.galcolors,而您应该使用 parent().parent() 上升了两个级别,直到 div.product。

关于javascript - jquery:运行脚本而不影响具有相同类的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26747339/

相关文章:

javascript - Azure DevOps 扩展将一个字段的值复制到另一字段

javascript - 从 AJAX 或 JQuery 运行 Python 脚本

javascript - 如何将中间件绑定(bind)到 socket.io 中的事件

javascript - 获取Json数据并在分割窗口onclick html上显示

JavaScript 不会在函数中输出值

jquery if div 有显示 none addclass 到父类

php - 保留复选框状态

jquery - 如何将外部网页加载到html页面的div中

javascript - 我需要在网页中制作一个按钮来放大和缩小(辅助功能控件)(禁用友好)

jquery - 3D Nav CSS3 旋转变换不起作用