jQuery:不使用id获取对特定元素的引用

jQuery: get a reference to a specific element without using id

本文关键字:元素 引用 获取 id jQuery      更新时间:2023-09-26

我正在使用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(不要问我为什么…),上面的标记被一遍又一遍地用来显示数据。因此,我需要能够在点击链接的"first-row"div中访问"hotel-info"div。

我试过这样做:

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

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

任何帮助都非常感谢!

提前感谢!

试试这个:

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

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

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

参考: .closest, .siblings


解释为什么你的代码不能工作:

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

给你.accommodation类的div,这个没有.hotel-info类的后代。

无论如何,在多个级别上使用这种遍历都不是一个好主意。如果稍微改变一下结构,代码就会中断。总是尝试使用不会在结构改变时中断的方法。

您没有使用ID元素来查找您想要的div,这是正确的:)

使用closestnextAll

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

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