function xmlParser(xml, projectName) {
var currentIndex = 0;
$(xml).find('entry').each(function(){
if($(this).attr('projectName').toLowerCase() == projectName) {
$previous = $(xml).find('entry')[currentIndex - 1]);
$project = $(this);
$next = $(xml).find('entry')[currentIndex + 1]);
//do something with these objects..
}
currentIndex++;
});
}
以下是一些示例代码。我有一个充满'entry'元素的XML文件。每个元素都有一个'projectName'属性。
代码基本上扫描XML以获取项目名称,比如说“Magic Giraffes”,返回与之匹配的XML元素,以及之前的&下一个项目。它有效...但我想知道它是否是最有效的方法。
了解我如何处理$ previous和$ next部分?它再调用.find()函数两次,然后根据当前索引的(-1)和(+1)获取元素。有没有更有效的方法来做到这一点?
答案 0 :(得分:0)
假设每个“条目”都是兄弟姐妹,中间没有其他元素:
$project = $(this);
$previous = $project.prev();
$next = $project.next();
其他
$project = $(this);
$previous = $project.prev('entry');
$next = $project.next('entry');
为了完全“优化”您的代码,您可以尽可能多地使用变量:
function xmlParser(xml, projectName) {
var exp = new regexp(projectName, "gi");
var $entries = $('entry', xml).filter(function() {
return exp.test( $(this).attr('projectName'));
});
$entries.each(function(){
$project = $(this);
$previous = $this.prev();
$next = $this.next();
//do something with these objects..
});
}
这里的“$ entries”变量阻止了对完整文档的无用访问,“$ this”通过jquery进行一些解析/选择(但这种影响仅限于性能)。
编辑:我确实在“过滤器”方法的帮助下更改了循环/匹配方法。注意:如果您确定条目中只有一个“projectname”,则可以删除“$ .each”图层,因为“$ entries”直接变为“$ project”
答案 1 :(得分:0)
您可以尝试使用entry [projectName = ...]选择器,并让jquery搜索正确的条目(请参阅:http://api.jquery.com/attribute-equals-selector/)但是您可能遇到区分大小写的问题。
当您需要下一个项目时,可以使用$ project.next()(参见:http://api.jquery.com/next/),与之前相同。
答案 2 :(得分:0)
您可以使用prev()和next()函数代替使用find函数。试试这个:
$previous = $(this).prev();
$project = $(this);
$next = $(this).next();
您还可以将选择器传递给那些选择器,以确保它只返回您想要的prev / next:
.prev('entry');
答案 3 :(得分:0)
如果您担心效率,可以尝试这样的事情。获得“入口”元素列表后,无需再次搜索它们 - 您需要的所有内容都在数组中。
function xmlParser(xml, projectName) {
var entries = $(xml).find('entry');
var previous;
var project;
var next;
$.each(entries, function(index, element)) {
if (element.attr('projectName').toLowerCase() == projectName) {
if (index > 0) {
previous = entries[index - 1];
} else {
previous = null;
}
project = entries[index];
if (index < entries.length - 1) {
next = entries[index + 1];
} else {
next = null;
}
}
});
}