2013-07-04 88 views
5

我有幾個自定義標籤的HTML。我想找到除了兩個之外的所有東西('開始','結束')並拆開它們。當我搜索文檔中的內容時,jQuery.find()似乎只能找到這些自定義標籤,而不是當我搜索jQuery對象時。我究竟做錯了什麼?jQuery不會找到自定義標籤

應該是不言自明的小提琴:

http://jsfiddle.net/hpNN3/2/

這裏的JavaScript部分:

var raw = $('pre').html(); 
var html = $(raw); 
var starts = html.find('start'); 
var spans = html.find('span'); 

//this returns nothing 
console.log(starts) 
// works - can find in object 
console.log(spans) 
//this works 
console.log($('start')); 


//only picks up spans, not annotations 
// I want this to return the innerHTML of the pre, stripping all tags except for 'start' and 'end' -- but retain the contents of those tags. 
var cleaned = html.find(':not(start, end)').each(function() { 
    $(this).contents().unwrap(); 
}); 

console.log(cleaned); 

$('#clean').html(cleaned) 

和HTML的例子:

<span class="ng-scope">CTAGCTCTCTGGAGATTAACGAGGAGAAATACTAGAtTGGTTCAT</span> 
<start feat="1" class="ng-scope"></start> 
<annotation index="1" class="ng-isolate-scope ng-scope" style="background-color: rgb(238, 153, 238); background-position: initial initial; background-repeat: initial initial;"> 
    <span tooltip="Another Promoter" tooltip-placement="mouse" tooltip-append-to-body="true" ng-transclude="" class="ng-scope"> 
     <span class="ng-scope">GATCATAAgcttgaat</span> 
    </span> 
</annotation> 
<end feat="1" class="ng-scope"></end> 
<span class="ng-scope">tagccaaacttatt</span> 

即應成爲:

CTAGCTCTCTGGAGATTAACGAGGAGAAATACTAGAtTGGTTCAT<start feat="1" class="ng-scope"></start>GATCATAAgcttgaat<end feat="1" class="ng-scope"></end>tagccaaacttatt

感謝

+4

HTML與自定義標籤不再是HTML –

+1

+2

爲什麼要用這種方式編寫HTML?標籤''有什麼好處'

'或''?更不用說,使用選擇器'$('。className')'會更快。 – Dom

回答

3

你的問題出在你的初始變量:

var raw = $('pre').html(); 
var html = $(raw); 

這相當於var html = $($('pre').html()),不會任何元素匹配。其原因在於,由於選擇不被#.之前,它正在字面上尋找標籤:

<<start feat="11" class="ng-scope"></start><annotation index="11" class="ng-isolate-scope ng-scope" style="background-color: rgb(238, 204, 153); background-position: initial initial; background-repeat: initial initial;">> 

等等

這裏是一個演示我的意思: http://jsfiddle.net/hpNN3/7/


只要做到以下幾點:

var html = $('pre'); 

DEMO: http://jsfiddle.net/hpNN3/6/

+0

好的 - 但這隻會解開他們,如果他們在DOM中。我不想直接操作DOM - 我想創建一個對象(不綁定到文檔)並在那裏進行轉換。 –