14

我有这个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?

4

7 回答 7

24

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

<div class="potato" />

您可以像这样访问:

$('#bottom > .potato').html('Idaho');
于 2009-06-15T18:43:49.063 回答
19

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

为了得到你想要的 div,这对我有用:

$('#bottom').find('#potato'); 
于 2012-01-09T21:05:27.923 回答
5

一方面,您不能拥有与另一个具有相同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
});
于 2009-06-15T18:46:32.520 回答
4

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

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

https://jsfiddle.net/wzezr706/

于 2016-03-26T06:29:57.097 回答
1

无需在所有内容上都放置类,但您应该对所有内容都有唯一的 id。除此之外,试试这个:

$("#bottom + div").html('Idaho');
于 2009-06-15T18:49:00.537 回答
0

尝试这个:

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

或者

$("#bottom #potato:last").html('Idaho');
于 2009-06-15T18:51:39.207 回答
-1

您的 HTML 无效,因为您有非唯一id的 s

于 2009-06-15T19:05:41.363 回答