这是您需要的“更漂亮”版本(没有评估,没有全局变量,正式参数,字符串中没有丑陋的代码),而不是在原型上设置它,因为这不适用于 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;
}
测试用例
使用 Firefox 访问 google.com,在控制台中输入上述代码,然后输入以下内容:
// 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');
更新
如果您希望能够按照您提到的那样执行 +=,我的解决方案将不起作用。我认为最优雅的解决方案是使用如下回调循环。
/**
* 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";
});