jQuery 获取项目父项
我正在尝试使用以下代码获取项目的父项目。
(父级的内容)
例如。在下面的示例中,“Item 1.1”的父项将是“Item 2”。
项目:
<ul class="sortable" id="page-list">
<li><div>Item 1</div></li>
<li><div>Item 2</div>
<ul>
<li><div>Sub Item 1.1</div></li>
<li><div>Sub Item 1.2</div></li>
<li><div>Sub Item 1.3</div></li>
<li><div>Sub Item 1.4</div></li>
</ul>
</li>
</ul>
JavaScript:
function saveNewList() {
//get DIV contents in order
var divContents = [];
$("ul.sortable > li div").each(function() { divContents.push($(this).text()) });
var quotedCSV = '"' + divContents.join('", "') + '"';
$("#results").text(quotedCSV);
//get DIV parents' contents in order
var divParents = [];
// something needs to go here...
var quotedCSVparents = '"' + divParents.join('", "') + '"';
$("#results2").text(quotedCSVparents);
}
I am trying to get the parent item of an item with the below code.
(the content of the parent)
ex. the parent of "Item 1.1" would be "Item 2" in the below example.
Items:
<ul class="sortable" id="page-list">
<li><div>Item 1</div></li>
<li><div>Item 2</div>
<ul>
<li><div>Sub Item 1.1</div></li>
<li><div>Sub Item 1.2</div></li>
<li><div>Sub Item 1.3</div></li>
<li><div>Sub Item 1.4</div></li>
</ul>
</li>
</ul>
Javascript:
function saveNewList() {
//get DIV contents in order
var divContents = [];
$("ul.sortable > li div").each(function() { divContents.push($(this).text()) });
var quotedCSV = '"' + divContents.join('", "') + '"';
$("#results").text(quotedCSV);
//get DIV parents' contents in order
var divParents = [];
// something needs to go here...
var quotedCSVparents = '"' + divParents.join('", "') + '"';
$("#results2").text(quotedCSVparents);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将向上遍历到最近的具有子
的
,然后向下遍历到其第一个
子级并获取文本。
当您位于上部
元素时,这也会获取文本。这是想要的吗?如果没有,只需添加一个
.parent()
,如下所示:这应该避免在您不在内部
中时获取文本。
This will traverse up to the nearest
<li>
that has a sub<ul>
then down to its first<div>
child and get the text.This would also get the text when you're in the upper
<li>
element. Is this desired? If not, just add a.parent()
like this:This should avoid getting the text when you're not in the inner
<li>
.从技术上讲,“子项目 1.1”的父项是包裹在其周围的
标签:
< div>子项目 1.1
但您可以使用
.parent()
移动在层次结构中向上一级:第一个
.parent()
将您带到第二个将您带到
>,第三个将您带到主
,而
.find('div')
将您带回到Item 2< ;/div>
the parent of "Sub Item 1.1" is technically the
<li>
tag wrapped around it:<li>
<div>Sub Item 1.1</div>
</li>
but you can use
.parent()
to move up a step in the hierarchy:first
.parent()
takes you to the<li>
2nd one takes you to the<ul>
, 3rd one takes you to the main<li>
and.find('div')
brings you back down to the<div>Item 2</div>