比较两大组属性

2024-04-29 02:41:20 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有一个Django视图,它有两个函数:

第一个函数使用XSLT样式表呈现一些XML,并生成一个包含1000个子元素的div,如下所示:

<div id="myText">
    <p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">✽</a></strong>Lorem ipsum</p>
    <p id="p2"><a class="note-p2" href="#" style="display:none" target="bot">✽</a></strong>Foo bar</p>
    <p id="p3"><a class="note-p3" href="#" style="display:none" target="bot">✽</a></strong>Chocolate peanut butter</p>
     (etc for 1000 lines)
    <p id="p1000"><a class="note-p1000" href="#" style="display:none" target="bot">✽</a></strong>Go Yankees!</p>
</div>

第二个函数使用另一个样式表呈现另一个XML文档,以生成如下所示的div:

^{pr2}$

我需要查看myText中哪些元素的类与myNotes中的元素匹配,并显示它们。我可以使用以下jQuery执行此操作:

$('#myText').find('a').each(function() {
    var $anchor = $(this);
    $('#myNotes').find('cite').each(function() {
        if($(this).attr('class') == $anchor.attr('class')) {
            $anchor.show();
    });
});

然而,对于大量的比较来说,这是非常缓慢和低效的。在

最快/最有效的方法是什么-是否有一个jQuery/js方法对大量的项目是合理的?或者,在将Django代码传递给模板之前,是否需要重新设计Django代码来完成这项工作?在


Tags: django函数divnoneid元素targetstyle
3条回答

这样的怎么样:

http://jsfiddle.net/9eXws/

$('#myText a').each(function() {
    $("#myNotes ." + $(this).attr('class')).show();
});​

它不执行内部each,而是将当前a元素的类追加到选择器中,并对找到的任何项执行show()。在

我认为内部的find对于外部的each的每次迭代都是重复执行的。尝试在循环开始之前将匹配的元素存储在变量中。我还调整了您的解决方案,通过DOM属性获得类名,而不是使用jQuery的attr

var $cites = $('#myNotes').find('cite');
$('#myText').find('a').each(function() {
    var anchor = this;
    $cites.each(function() {
        if(this.className == anchor.className) {
            $anchor.show();
    });
});

为了获得最佳性能,请创建一个索引,然后重复使用:

function revealCite() {
  var cites_index = $("#myText").data("cites_index");

  // if no cached index exists, prepare one (one-time hit code section)
  if (!cites_index) {
    var cites = $("#myNotes cite");
    var cites_count = cites.length();
    var cites_index = {};

    for (var i=0; i<cites_count; i++) {
      var cite = cites[i], group = cites_index[cite.className];
      if (!group) cites_index[cite.className] = [];
      group.push(cite);
    }
    $("#myText").data("cites_index", cites_index);
  }

  // use the index to work with related elements ("this" must be an <a> element)
  $(cites_index[this.className]).show();
}

现在按您喜欢的任何方式触发上述函数:

^{pr2}$

PS:您也可以这样做,代替for循环:

cites.each( function() {
  var group = cites_index[this.className];
  if (!group) cites_index[this.className] = [];
  group.push(this);
});

但它的代码行数是相同的,而且可能有点慢。在

相关问题 更多 >