2012-02-08 74 views
6

也許這是非常基本的,但我都很困惑。 我有一個簡單的HTML頁面與許多部分(股利)。我有一個字符串包含javascript中的html標籤。代碼如下:如何使用javascript或jquery從字符串中提取html標記的內容?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script type="text/javascript"> 
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>"; 
</script> 
</head> 
<body> 
<div id="title1"></div> 
<div id="new1"></div> 
<div id="title2"></div> 
<div id="new2"></div> 
</body> 
</html> 

我想提取的HTML標籤(從JavaScript中的字符串)的內容,並顯示在我的html頁面中所需的部分的內容。

即我要在<div id="title1">和「This is a paragraph1」中顯示「This is a heading1」。在<div id="new1">中顯示,對於第二對標籤也是如此。

我需要所有這些只在客戶端工作。我試圖使用HTML DOM getElementByTagName方法,它變得太複雜了。我對jquery知之甚少。我很困惑。我不明白如何去做。你能指導我使用什麼 - JavaScript或jQuery和如何使用它?有沒有一種方法來識別字符串並遍歷它?

如何從str1中提取「This is heading1」(以及包含在html標籤中的類似內容)?我不知道這些索引,因此不能在javascript中使用substr()或substring()函數。

回答

9

使用.text()同時作爲「吸氣」和「二傳手」我們只是重複的模式:

  • 目標,我們希望以填充頁面上的元素
  • 給它的內容從 字符串

jsFiddle

<script type="text/javascript"> 
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>"; 
$(function(){ 
    var $str1 = $(str1);//this turns your string into real html 

    //target something, fill it with something from the string 
    $('#title1').text($str1.find('h2').eq(0).text()); 
    $('#new1').text($str1.find('p').eq(1).text()); 
    $('#title2').text($str1.find('h2').eq(1).text()); 
    $('#new2').text($str1.find('p').eq(1).text()); 
}) 
</script> 
+0

Thnks ..它的工作.. – user1196522 2012-02-08 09:41:17

1

嗯,

首先,你應該說明你是如何從你自己的html獲得源html的。如果您使用的是Ajax,則應該將源代碼標記爲html,甚至是xml。

0

的document.getElementById( '{元件的ID}')的innerHTML

如果使用jQuery $( '選擇')的HTML()。;

<div id="test">hilo</div> 
<script> 
alert($('#test').html()); 
<script> 
0

讓我前言我與我不認爲我完全明白你想要做什麼......但是我覺得要替換一些(雖然你使它聽起來像所有的)知識回答與一些數據源的HTML。

我操縱一個簡單的例子是這裏的jsfiddle:

http://jsfiddle.net/rS2Wt/9/

這確實一個簡單的替換使用上的目標DIV jQuery的。

希望這會有所幫助,祝你好運。

2

恕我直言,您可以分兩步做jQuery中:

步驟1)解析字符串轉換成XML/HTML文檔。

至少有兩種方法可以做到這一點:

一)正如Sinetheta

var htmlString = "<html><div></div></html>"; 
var $htmlDoc = $(htmlString); 

b)使用parseXML

提到
var htmlString = "<html><div></div></html>"; 
var htmlDoc = $.parseXML(htmlString); 
var $htmlDoc = $(htmlDoc); 

請參閱http://api.jquery.com/jQuery.parseXML/

步驟2)選擇t從XML/HTML文檔中分支。

var text = $htmlDoc.text(jquery_selector); 

請參閱http://api.jquery.com/text/

相關問題