【问题标题】:Selecting child div by id knowing a parent div id with JQuery selectors通过 id 选择子 div 知道使用 JQuery 选择器的父 div id
【发布时间】:2016-03-26 14:29:57
【问题描述】:

我有这个 html:

<div id="top">
<div id="potato"></div>
</div>
<div id="bottom">
<div id="potato"></div>
</div>

我正在尝试使用 JQuery 来访问底部的土豆 div,但没有以下工作。

$('#top #potato').html('Russet');
$('#bottom #potato').html('Red');

$('#top > #potato').html('Russet');
$('#bottom > #potato').html('Red');

$('#potato').html('Idaho');

所有这些只是修改顶部的 div 而不是底部的。如何修改底部的div?

【问题讨论】:

  • @Matthew 这里有答案吗?你为什么不关注你的问题?

标签: jquery-selectors


【解决方案1】:

所有元素都必须有唯一的ID,在这种情况下你可以使用class属性,这样你就有了

<div class="potato" />

您可以这样访问:

$('#bottom > .potato').html('Idaho');

【讨论】:

  • 如果您使用变量,则不起作用,例如:$(a > b),它仅适用于 CSS 选择器语句。 $(a).find(b) 语法在多种情况下更可靠。
【解决方案2】:

我刚刚遇到了这个问题。虽然确实不应该有两个具有相同 ID 的项目,但它确实发生了。

要获得你想要的 div,这对我有用:

$('#bottom').find('#potato'); 

【讨论】:

    【解决方案3】:

    一方面,您不能拥有与另一个具有相同 id 的元素。 Id 是唯一的,但类名可以使用任意多次

    <div id="top">
     <div id="potato1"></div>
    </div>
     <div id="bottom">
     <div id="potato2"></div>
    </div>
    

    jquery 是这样的:

    $(function{
     $("#potato2").html('Idaho'); //if you're going to name it with an id, 
      //  that's all the selector you need
    });
    

    【讨论】:

    【解决方案4】:

    你发布和说的内容对我来说似乎不起作用。

    $('#top #potato').addClass('Russet');
    $('#bottom #potato').addClass('Red');
    

    https://jsfiddle.net/wzezr706/

    【讨论】:

      【解决方案5】:

      无需对所有内容都设置类,但您应该为所有内容设置唯一 ID。除此之外,试试这个:

      $("#bottom + div").html('Idaho');
      

      【讨论】:

        【解决方案6】:

        试试这个:

        $("#bottom #potato").html('Idaho');
        

        或者

        $("#bottom #potato:last").html('Idaho');
        

        【讨论】:

          【解决方案7】:

          您的 HTML 无效,因为您的 ids 不是唯一的

          【讨论】:

            猜你喜欢
            • 2021-04-26
            • 1970-01-01
            • 2010-12-28
            • 1970-01-01
            • 2012-10-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-07-21
            相关资源
            最近更新 更多