【问题标题】:jQuery: get a reference to a specific element without using idjQuery:在不使用 id 的情况下获取对特定元素的引用
【发布时间】:2012-02-10 15:04:33
【问题描述】:

我正在对 jquery 进行一些修改,以便在单击链接时显示隐藏的 div。这应该相当简单,但在这种情况下它有一个缺陷。我有以下标记:

<div class="first-row">
        <div class="week">
            <p>Uge 2</p>
            <p>(08-01-11)</p>
        </div>
        <div class="destination">
            <p><a href="#">Les Menuires</a></p>
            <p>(Frankrig)</p>
        </div>
        <div class="days">4</div>
        <div class="transport">Bil</div>
        <div class="lift-card">3 dage</div>
        <div class="accommodation">
            <p><a class="show-info" href="#">Hotel Christelles (halvpension)</a></p>
            <p>4-pers. værelse m. bad/toilet</p>
        </div>
        <div class="order">
            <p><a href="#">2149,-</a></p>
            <p class="old-price">2249,-</p>
        </div>
        <div class="hotel-info">
         <!-- The div I want to display on click -->
        </div>
    </div>

当我点击“show-info”链接时,我希望显示“hotel-info”div。 我的后端开发人员不希望我使用 id(不要问我为什么..),并且上面的标记被一遍又一遍地用于显示数据。因此,我需要能够访问单击链接的“第一行”div 中的“hotel-info”div。

我尝试过类似的操作:

$(document).ready(function() {
    $('.show-info').click(function() {
        var parentElement = $(this).parent().parent();
        var lastElementOfParent = parentElement.find(".show-hotel");
        lastElementOfParent.show();
    });
});

但是没有结果:-/这可能吗?

非常感谢任何帮助!

提前非常感谢!

【问题讨论】:

  • 您要显示的 div 名为 .hotel-info 但您的代码正在寻找 .show-hotel - 这只是一个错字吗?
  • Rory,谢谢 - 这是一个错字,但不幸的是它并没有解决我的问题 :(

标签: javascript jquery html xhtml jquery-traversing


【解决方案1】:

试试这个:

$('.show-info').click(function() {
    $(this).closest('.accommodation').siblings('.hotel-info').show();
});

更好的 imo,因为它将独立于 where 链接在一行中,如果每个“行 div”具有相同的类(我假设只有第一个具有类 first-row ),你可以这样做:

$(this).closest('.row-class').find('.hotel-info').show();

参考:.closest.siblings


解释为什么您的代码不起作用:

$(this).parent().parent();

为您提供 div.accommodation 类,而这个没有 .hotel-info 类的后代。

无论如何,将这种遍历用于多个级别并不是一个好主意。如果结构稍有改变,您的代码就会中断。始终尝试使用不会因结构更改而中断的方法。

【讨论】:

  • 嗨菲利克斯,这就像一个魅力! :) “第一行”这个名字可能会产生很大的误导,因为它实际上是每隔一行使用一次来使背景不同。所以第一个解决方案非常棒!非常感谢!
【解决方案2】:

你没有使用 ID 元素来找到你想要的 DIV 是对的 :)

使用closestnextAll

现场演示:http://jsfiddle.net/jomanlk/xTWzn/

$('.show-info').click(function(){
    $(this).closest('.accommodation').nextAll('.hotel-info').toggle();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 2013-09-27
    • 1970-01-01
    • 2014-12-14
    • 2021-10-03
    • 2011-10-27
    相关资源
    最近更新 更多