2012-11-07 56 views
0

我想使用JQuery從HTML字符串訪問元素。使用jQuery從HTML js對象中獲取控件/訪問元素

我有一個以下的AJAX函數,它在成功時返回HTML文本。我希望僅使用Jquery從HTML文本中提取標記的內容。

假設我有一個包含HTML內容的變量resp。我想訪問下面這個HTML裏面的內容標籤的內容..

var resp = "<html><head></head><body><form action="changePassword" name="fmChangePassword"> .... form elements .... </form></body> </html>" 
alert(resp); //this alerts the full HTML content properly     
alert($(resp).find("form").html()); //trial 1 -- returns NULL 
var test = $(resp).find("#changePassword"); //#changePassword is the ID of the form 
//alert(test.html()); 
displayChangePwdWindow(test); //need to pass the form content here   

我嘗試使用.find(),但沒有成功。

任何人都可以幫助我如何做到這一點?

+0

你到底想幹什麼?將在[jsfiddle](http://jsfiddle.net)中給出完整的代碼? – yosafatade

+0

嘗試提醒resp,你在那裏得到的HTML? – rahul

+0

你能顯示你的resp內容嗎?可能有些事情是錯的。因爲這應該工作得很好:http://jsfiddle.net/cEBsF/ –

回答

0

可能是這樣可以幫你

$.ajax({ 
    type: "POST", 
    url: url, 
    error: function(jqXHR, textStatus, errorThrown) { 
     alert(errorThrown); 
    }, 
    success: function(resp){ 
     var test = jQuery("<div/>").append(resp).find("#changePassword"); 
     alert(test.html()); 
     displayChangePwdWindow(test); //need to pass the form content here  
    } 
}); 
0

HTML
建立在你的身體隱藏的div ....

<div id="DIVID" style="display:none"></div> 

AJAX

$.ajax({ 
     type: "POST", 
     url: url, 
     error: function(jqXHR, textStatus, errorThrown) 
     {alert(errorThrown);}, 
     success: function(resp){ 

     $('#DIVID').html(resp); 
     var test = $("#changePassword").html(); 

     displayChangePwdWindow(test); //need to pass the form content here  
     } 
}); 

OR .. 你只需將它添加到一個身先..沒有必要創建一個隱藏的div

$.ajax({ 
     type: "POST", 
     url: url, 
     error: function(jqXHR, textStatus, errorThrown) 
     {alert(errorThrown);}, 
     success: function(resp){ 

     $(document.body).append(resp); 
     var test = $("#changePassword").html(); 

     displayChangePwdWindow(test); //need to pass the form content here  
     } 
}); 
+0

看着你看起來像你正在添加完整的'resp'內容(即完整的HTML內容)到DIV。我只是想''

'內容'resp' – DarkKnightFan

+0

我將全部html內容添加到div ...並使用選擇器來選擇ID ... $(「#changePassword」)。現在,將在身體中可用...所以這應該工作..... – bipen

1

也許您需要使用.filter()而不是.find()。 可以檢查演示first demo

也許如果你仍然想使用.find()你可以在HTML放到一個包裝查起。 你可以檢查第二個演示second demo