2013-07-04 86 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 - 我想创建一个对象(不绑定到文档)并在那里进行转换。 –