這是很難看到正是你正在嘗試做的,但這裏有一對夫婦的功能,可以幫助你和他們使用的例子(我明白你的要求)
function getTextNodes(el) {
var nodes = [];
if(el.length) { //perhaps a better test for an array/collection of objects is required here?
for(var i = 0, j = el.length; i < j; i++) {
//call this function with each item in the array/collection
nodes = nodes.concat(arguments.callee(el[i]));
}
return nodes;
}
for(var i = 0, j = el.childNodes.length; i < j; i++) {
var node = el.childNodes[i];
if(node.nodeType == 3) {
//ignore whitespace
if(/^\s+$/.test(node.nodeValue)) continue;
nodes.push(node);
} else {
//call this function with this child node
nodes = nodes.concat(arguments.callee(node));
}
}
return nodes;
};
function getByClassName(className) {
//some browsers already have this function
if(document.getElementsByClassName) {
return document.getElementsByClassName(className);
}
var els = [];
var candidates = document.getElementsByTagName('*');
for(var i = 0, j = candidates.length; i < j; i++) {
if(candidates[i].className.indexOf(className) > -1) {
els.push(candidates[i]);
}
}
return els;
};
function trim(str) {
return str.replace(/^\s+/, '').replace(/\s+$/, '');
};
USE :
//grab all the textnodes in elements with class foo
var textNodes = getTextNodes(getByClassName('foo'));
//loop through the data performing your replacement
for(var key in data) {
if(!data[key].origin) continue;
for(var i = 0, j = textNodes.length; i < j; i++) {
if(trim(data[key].origin) == trim(textNodes[i].nodeValue)) {
textNodes[i].nodeValue = 'assign me';
}
}
}
上幾個百分點的原始
- 這是低效的 - 爲您的數據y的每一個循環ou再次找到foo元素中的textnode,你只需要找到它們一次
- jQuery中的鏈接確實允許非常簡潔的代碼,但不能讓它理解。我覺得上面的點是想鏈一切
更好的jQuery
var textnodes = jQuery(".foo")
.find("*")
.andSelf()
.contents()
.filter(function() {
return this.nodeType === 3;
});
jQuery.each(data.results, function(index, value) {
textnodes.filter(function() {
// Only match when contains 'simple string' anywhere in the text
if(value.origin != "") {
return this.nodeValue === (value.origin);
}
})
.each(function(){
this.nodeValue = "assign me";
});
});
什麼是落後不想使用jQuery推理的結果? – 2010-01-27 22:54:45
打開jQuery.js並開始查看您正在使用的每個函數背後的代碼。當你編寫jQuery代碼 – PetersenDidIt 2010-01-28 03:43:44