2014-10-07 79 views
0

比如我的HTML代碼:jQuery的過濾器標籤,並加入爲html

aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong> <a href="d">aaaa</a> 

而且我想只留下div.inptag標籤,並刪除所有其他標籤,而是從其他標籤離開的innerText。

我寫了jQuery代碼:

dat = $('<div/>').html('aaa<b>aaa</b><div class="inptag">ccc</div>') 
.find('*:not(div.inptag,div.inptag>div.typ,div.inptag>input)').contents().unwrap(); 

...我不知道如何得到結果爲標準的HTML代碼。現在我有[object Object]和.join('')不起作用。

+1

這樣的事情? http://jsfiddle.net/sx0q6d44/ – charlietfl 2014-10-07 20:27:45

+0

是這樣的,但來自變量,並將結果html保存到變量 – Peter 2014-10-07 20:31:36

+0

只需使用'html()'上的jQuery對象來獲取包裝div的html – charlietfl 2014-10-07 20:36:42

回答

1

我假設你想在這裏輸出一個字符串?如果是這樣,這看起來完成你所需要的。

var inputStr = 'aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong> <a href="d">aaaa</a>', 
    elt = $('<div/>').html(inputStr), //jquery will convert this to DOM elements 
    badTags = elt.find(':not(div.inptag)'), //find the elements that are not divs with a class of inptag 
    index, 
    outputStr = '' + inputStr; //making a copy of inputStr 

//cycle through all of the bad tags that we found 
for(index = 0; index < badTags.length; index++) { 
    //replace any instances of the outer html with instances of the inner text 
    outputStr = outputStr.replace(badTags[index].outerHTML, badTags[index].innerText); 
} 

alert(outputStr); 

小提琴here

+0

http:// jsfiddle.net/o7xg4xv6/3/ - 這就是我想要的:)謝謝 – Peter 2014-10-07 20:40:43

+0

很高興我可以幫忙。 – Ixonal 2014-10-07 20:41:53