2013-08-03 74 views
0

我認爲這並不罕見,所以我在這裏搜索,但找不到足夠的方法。jQuery - 替換'find'元素的HTML

基本上,我想替換特定元素下的字符串 - pre

  1. sourceHTMLstrings
  2. 渦卷與一個div
  3. 轉換(套)以jQueryObject
  4. 找到pre
  5. 獲得的每個pre
  6. 的HTMLstrings從A替換到HTMLstrings B內
  7. 用新的HTML字符串重構每個pre
  8. 重構jQueryObject或者sourceHTMLstrings

所以,這裏是我的嘗試:

String.prototype.replaceAll = function (org, dest) 
    { 
     return this.split(org).join(dest); 
    }; 
var wrap = function (data) 
    { 
     return '<div>' + data + '</div>'; 
    }; 

// Data is a string which contains `pre` elements 
var $data2 = $(wrap(Data)) 
       .find('pre') //behavior is confirmed to find several `pre`; so far so good 
       .html(this.html().replaceAll(A, B)); 
       //Uncaught TypeError: Object #<Object> has no method 'html' 

..... 

var $data2 = $(wrap(Data)) 
       .find('pre') //behavior is confirmed to find several `pre`; so far so good 
       .html(this.replaceAll(A, B)); 
       //Uncaught TypeError: Object #<Object> has no method 'replaceAll' 

基本上,我跟不上每個對象的方式方法之間傳遞。

我也試着用each方法沒有成功。你有這個好主意嗎?

編輯:

答案是

var $data2 = $("<div/>"); 

$data2.html(Data).find("pre").html(function(_,h){ 
     return h.replaceAll(A, B); 
}); 

然後$數據2 .....

$data2 = $("<div/>").html(Data).find("pre").html(function(_,h){ 
      return h.replaceAll(A, B); 

結果只pre集合。不是整個文檔範圍。

我認爲這是一個好的或壞的例子,通過破壞性的價值來展示問題。

即使jQuery是非常功能範例,這是如此糟糕。

回答

1

如果你改變html功能

.html(this.replaceAll(A, B)); 

這個它會工作:

.html(function(_,h){ 
    return h.replaceAll(A, B); 
}); 

而作爲一個旁註,你可以把它簡單:

var $data2 = $("<div/>").html(Data).find("pre").html(function(_,h){ 
     return h.replaceAll(A, B); 
}); 

編輯:

如果您想獲取Data變量中的entrie HTML,請在更改HTML後嘗試使用end()。這將重置遍歷並將其恢復到<div/>的級別。

var $data2 = $("<div/>").html(Data).find("pre").html(function (_, h) { 
    return h.replaceAll(A, B); 
}).end(); 

上述代碼將返回我們創建的div。它的內容將是pre和其他東西。要獲得這些東西,請在end()之後添加children()。這會將Data中的所有內容轉換爲DOM對象。

var $data2 = $("<div/>").html(Data).find("pre").html(function (_, h) { 
    return h.replaceAll(A, B); 
}).end().children(); 

演示:http://jsfiddle.net/hungerpain/jRjQC/

+0

感謝hungerpain,漂亮的技術我學習。但是,代碼不起作用。請檢閱我的編輯。 –

+0

@KenOKABE我沒有得到你..你能否詳細說明一下?你需要變量中的'pre'的整個集合嗎?或整個'文檔'?它極其不明確。 – krishgopinath

+0

@KenOKABE檢查我編輯的答案 – krishgopinath

0
var $data2 = $(wrap(Data)).find('pre').html().replaceAll(A, B); 
+0

我覺得這個結果只是第一次打。不工作。 –