下面是你需要什麼,而不是設置它的原型,因爲一個「漂亮」的版本(沒有的eval,沒有全局,正式參數,字符串內沒有的fugly代碼)這對IE不起作用。
/**
* Sets a property on each of the elements in the list
* @param {NodeList} list
* @param {string} prop The name of property to be set,
* e.g., 'style.backgroundColor', 'value'.
* @param {mixed} value what to set the value to
*/
function setListProp(list, prop, value) {
for (var i = 0; i < list.length; i++) {
setProp(list[i], prop, value);
}
}
/**
* Avoids the use of eval to set properties that may contain dots
* Why avoid eval? eval is slow and could be dangerous if input comes from
* an unsanitized source
* @param {object} el object that will have its property set
* @param {string} propName ('value', 'style.backgroundColor')
* Example: setProp(node, 'style.backgroundColor', "#ddd");
*/
function setProp(el, propName, value) {
var propList = propName.split('.');
// Note we're not setting it to the last value in the property chain
for (var i=0; i < propList.length - 1 ; i++) {
el = el[propList[i]];
}
var lastProperty = propList[propList.length -1];
el[lastProperty] = value;
}
測試用例 訪問google.com使用Firefox,輸入上面的代碼到控制檯,然後輸入以下命令:
// Set tooltip on links
setListProp(document.getElementsByTagName('a'), 'title', 'YEAH it worked');
// Set bg to red on all links
setListProp(document.getElementsByTagName('a'), 'style.backgroundColor', '#f00');
UPDATE 我的解決方案贏得了」如果你希望能夠像你剛纔提到的那樣做,我認爲最優雅的解決方案是使用如下的回調循環。
/**
* This exists in many libs and in newer versions of JS on Array's prototype
* @param {Object[]} arr The array that we want to act on each element.
* Does not work for sparse arrays
* @param {Function} callback The function to be called for each element, it will be passed
* the element as its first argument, the index as the secibd
*/
function iterate(arr, callback) {
for (var i=0,item; item=arr[i]; i++) {
callback(item, i);
}
}
然後,你可以這樣調用
var as = document.getElementsByTagName('a');
iterate(as, function(el, index) {
el.style.backgroundColor = 'red';
el.innerHTML += "Whatever";
});
是的,你不需要EVAL這一點。 也因爲你實際上只有2個參數,爲什麼不命名他們和使用參數[]數組? – BYK 2009-04-19 10:52:27