jQuery before()两次添加一个元素

时间:2014-08-13 05:08:08

标签: jquery

我正在尝试使用以下jquery代码将i元素添加到列表中:

(function ($, Drupal, window, document, undefined) {


// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {

    $('.menu-mlid-487 a').before('<i class = "icon-overview"></i>');
    $('.menu-mlid-487 a').before('<i class = "icon-admissions"></i>');
    $('.menu-mlid-487 a').before('<i class = "icon-curriculum"></i>');
    $('.menu-mlid-487 a').before('<i class = "icon-faculty"></i>');
    $('.menu-mlid-487 a').before('<i class = "con-testimonial"></i>');
    $('.menu-mlid-487 a').before('<i class = "icon-calendar"></i>');

  }
};

})(jQuery, Drupal, this, this.document);

然而,结果是i元素被打印两次。

<ul class="menu clearfix">
  <li class="first leaf active-trail active menu-mlid-487">
    <i class = "icon-overview"></i>
    <i class = "icon-overview"></i>
    <a href="/emba" title="" class="sf-depth-2 active-trail active">Overview</a>
  </li>
</ul>

我尝试使用append()但它也会打印两次。我使用的代码有什么问题吗?

更新

通过Drupal主题.info文件调用js文件,如下所示:

stylesheets[all][] = css/style.css
stylesheets[print][] = css/print.css

scripts[] = js/script.js

regions[header] = Header
regions[navigation] = Navigation
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[content] = Content
regions[under_content_wide] = Under Content Wide
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

相关行是脚本[]

1 个答案:

答案 0 :(得分:0)

也许$('.menu-mlid-487 a')匹配两个元素?然后,当$('.menu-mlid-487 a').addClass("icon-overview");两个元素具有相同的类"icon-overview"时。

使用console.log输出{{​​1}}。

是的,就像每个人都说的那样,你给我们留下了猜测和猜测,因为你没有提供足够的信息。我想如果你找到足够的信息来正确地提出你的问题,你会自己找到答案:)