我認爲這並不罕見,所以我在這裏搜索,但找不到足夠的方法。jQuery - 替換'find'元素的HTML
基本上,我想替換特定元素下的字符串 - pre
。
- sourceHTMLstrings
- 渦卷與一個div
- 轉換(套)以jQueryObject
- 找到
pre
- 獲得的每個
pre
- 的HTMLstrings從A替換到HTMLstrings B內
- 用新的HTML字符串重構每個
pre
- 重構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是非常功能範例,這是如此糟糕。
感謝hungerpain,漂亮的技術我學習。但是,代碼不起作用。請檢閱我的編輯。 –
@KenOKABE我沒有得到你..你能否詳細說明一下?你需要變量中的'pre'的整個集合嗎?或整個'文檔'?它極其不明確。 – krishgopinath
@KenOKABE檢查我編輯的答案 – krishgopinath