2013-04-28 44 views
-1

刪除重複的字符串這是他們的Attirbutes作者動態創建的HTML列表:如何使用jQuery從HTML

<span class="authors"> 
    <a href="/url_one">Author One Name</a><span> - <a href="http://wsj.com">Author Attirbute String</a></span>, 
    <a href="/url_one">Author Two Name</a><span> - <a href="http://wsj.com">Author Attirbute String</a></span>, and 
    <a href="/url_one">Author Three Name</a><span> - <a href="http://wsj.com">Author Attirbute String</a></span> 
</span> 

我如何使用jQuery剝離每個連續<span> <a href="http://wsj.com">Author Attirbute String</a></span>只留下最後一個,如果他們是相同的和連續的?

因此,可以說我有三個作者所有的「華爾街日報」同屬性附加傷害......我試圖使這個:

作者一個名字 - 華爾街日報,作者的兩個名稱 - 華爾街日報,和作者三名 - 華爾街日報

是這樣的:

作者一個名字,作者兩名,以及作者三名 - 華爾街日報

只有屬性相同且連續時才能工作,否則中止該功能。

一對夫婦的其他因素:

  1. 可以有每HTML實例1至4的作者。
  2. 在頁面上可能有幾個這些作者列表的實例,它們都需要處理。

請幫忙,如果亞能!我知道這很複雜...

這是我正在做的非簡化示例...它是一個Drupal站點,屬性由JQuery從使用此功能的代碼中的標題標記生成我想修改,以便移除重複:

$(function() { 
    $('span.authors a').each(function() { 
    $('a[href^="/authors/"]').attr('title'); 
    if ($(this).attr('title')) { var attrarray = $(this).attr('title').split('|'); 
     if (attrarray[1]) { var thespan = '<span> ~ <a href="http://' + attrarray[1] + '">' + attrarray[0] + '</a></span>'; } 
     else { var thespan = '<span> ~ ' + attrarray[0] + '</span>'; } 
     $(this).after(thespan); } 
    }); 
}); 

這裏是頁面的一個例子:http://kpbj.com/authors/dee_ann_durbin

+0

嗯......我還應該解釋一下,JQuery也是爲標題標籤中的作者生成屬性的。我將在編輯中附加該代碼。 – 2013-04-28 15:27:07

+0

例如,Iain Banks和Iain M.Banks會發生什麼?名稱不同,但據推測,該鏈接應該/應該指向同一個地方? ([他們是同一作者](http://en.wikipedia.org/wiki/Iain_M_Banks),順便說一句,只是要清楚。) – 2013-04-28 15:30:01

+0

在每一行中永遠不會有同一作者的情況。 – 2013-04-28 15:43:25

回答

3
// Get spans. 
var attributes = $('.authors').children('span'); 

// Save first value in variable to compare it to other elements. 
var content = attributes.first().html(); 

// Iterate through all children and compare their values to the first one. 
$.each(attributes, function(index, item){ 
     // Abort if not the same. 
     if ($(item).html() != content) return; 
    }); 

// All are the same. Remove all except the last one. 
$.each(attributes, function(index, item) { 
     if (index != attributes.length - 1) $(item).remove(); 
    }); 

這裏的fiddle

更新:根據意見
,這裏的更新fiddle

+0

我喜歡這個。我會看看我是否可以將其納入我的代碼。我只希望我不會因爲對瀏覽器的JavaScript處理能做多少的期望而大傷腦筋。 – 2013-04-28 15:50:43

+0

我不認爲這會是一個問題,因爲瀏覽器可以處理更多/更復雜的腳本。無論如何,祝你好運:) – Kamyar 2013-04-28 15:52:21

+0

我想我會想出一個辦法,只是不添加它們,而不是後來刪除它們。 – 2013-04-28 16:51:10

0

我不喜歡這種風格,但你去那裏。 。 。解決您的問題。

var allAuthors = []; 
    var countAuthors = $(".authors span").length; 
    $(".authors span").each(function(i){ 
     var authorSpan = $(this); 
     if(allAuthors.indexOf($(this).html()) == -1){ 
      authorSpan.hide(); 
      allAuthors.push($(this).html()); 
     }else{ 
      if(countAuthors-i>1){ 
       authorSpan.hide(); 
      } 
     } 
    });