基本上,我试图以递归方式向后读取dom树以生成路径。读取dom从单击的项目开始,然后转到父项,收集属性值并按照严格的命名约定继续向上,直到没有更多父项。我无法搞清楚,但觉得我走的很好。我想尽可能多地从概念上学习。感谢您的任何反馈。的 Here's a JsFiddle
我希望点击的结果,无论多深,都会导致生成的路径几乎像面包屑一样。问题是我似乎无法格式化字符串并以正确的顺序输出它。
所需的输出:/ books / 1 / chapter / 1 / pages / 1
HTML
<div class="list-group" data-type="books">
<a href="#" class="book list-group-item" data-id="1">Book 1</a>
<div class="list-group" data-type="chapters">
<a href="#" class="chapter list-group-item" data-id="1">Chapter 1</a>
<div class="list-group" data-type="pages">
<a href="#" class="page list-group-item" data-id="1">Page 1</a>
<a href="#" class="page list-group-item" data-id="2">Page 2</a>
<a href="#" class="page list-group-item" data-id="3">Page 3</a>
</div>
</div>
</div>
JQUERY
$(document).on('click','.list-group-item', function(e){
e.stopPropagation();
path = getDomData($(this)); // books/1/chapter/2/page/1
});
function getDomData(activeElement){
var activeElementId = activeElement.data('id');
var activeElementParent = activeElement.closest('.list-group');
var activeElementParentType = activeElementParent.data('type');
var activeElementParentParent = activeElementParent.parent('.list-group-item');
result = activeElementParentType +'/'+ activeElementId +'/';
if(activeElementParentParent.length > 0){
getDomData(activeElementParentParent);
}
return result;
}
答案 0 :(得分:2)
在jquery对象上使用.parents().each(function(){})
迭代父项集合,该对象将沿树向上移动:
//use the dollar-sign at beginning if the argument name
//to hint that the fn is expecting a jquery object:
function getDomData($activeElement){
//start with the element that was clicked:
var path = '/' + $activeElement.data('id');
//then go over each ancester up the tree, check which
//type it is, and append to the beginning of your path accordingly:
$activeElement.parents().each(function(){
if($(this).hasClass('list-group-item')){
path = ('/' + $(this).data('id')) + path;
}
else if($(this).hasClass('list-group')){
path = ('/' + $(this).data('type')) + path;
}
});
return path;
};
答案 1 :(得分:1)
<强>解决方案:强>
<强> Fiddle 强>
$(document).on('click','.list-group-item', function(e){
e.stopPropagation();
path = getDomData($(this)); // books/1/chapter/2/page/1
console.log(path);
});
function getDomData(activeElement){
var activeElementId = activeElement.data('id');
var activeElementParent = activeElement.closest('.list-group');
var activeElementParentType = activeElementParent.data('type');
var activeElementParentParent = activeElementParent.siblings('.list-group-item');
var result = activeElementParentType +'/'+ activeElementId +'/';
if(activeElementParentParent.length > 0){
return getDomData(activeElementParentParent) + result;
}
return result;
}
<强>的变化:强>
var
声明结果(因此,它的值不会在递归中被覆盖)if
内返回递归结果(与当前结果连接)activeElementParent.parent
更改为activeElementParent.siblings
ajaxPath
的回复更改为result
(ajaxPath
未知)console.log(path);
(请参阅控制台中的结果)