1

これは、少なくとも現時点では純粋な実験ですが、興味があります: メソッドを (プロトタイピングを介して) 要素のコレクションにアタッチする方法はありますか? 次のコードをテストしました。

<div>a</div>
<div>b</div>
<div>c</div>
<script>
NodeList.prototype._ = function(s)
 {
    for (x = 0; x < this.length; x++)
     {
        eval('this[x]' + '.' + s);
     }
    return this;
 }
document.getElementsByTagName('div')._("style.backgroundColor = 'red'")._('innerHTML += x');
</script>

現時点では、Opera で完全に動作します。予想どおり、すべての div 要素に対して _ メソッドが呼び出され、渡された文字列が各要素に対して順番に eval()されます。_ メソッドは連鎖を可能にすることに注意してください。また、_ を呼び出して予測されたxイテレータ変数を各要素の innerHTML に追加することも示されています。

では、2つ質問...

まず、これについてもっと良い方法はありますか?私は長い間、私ができることを望んでいましたdocument.getElementsByTagName('div').style.backgroundColor = "red";が、残念ながら、それはまだ実現していません. これが、私が最初にこれを行っている理由であり、メソッドに簡潔な名前を付けた理由です。私はそれをできるだけ忠実にエミュレートしようとしています。

第二に、これが正しい使い方であると仮定すると、どうすれば Firefox で動作させることができるでしょうか? そのブラウザの相当するものはNodeListですがHTMLCollection、後者のプロトタイプを作成しようとしてもうまくいきません。提案?

4

2 に答える 2

1

実行可能な解決策としてとどまることができると思われるものを作成しました。このメソッドを使用して要素のコレクションをチェーン変更することについて根本的に悪いことはありますか?

<script>
_ = function()
 {
    for (x = 0; x < arguments[0].length; x++)
     {
        for (y = 0; y < arguments[1].length; y++)
         {
            eval('arguments[0][x]' + '.' + arguments[1][y]);
         }
     }
 }
</script>

使用法:

divs = document.getElementsByTagName('div');
_(divs, ["style.color = 'red'", "innerHTML += x"]);
于 2009-03-02T21:33:16.620 に答える
0

これは、必要なものの「よりきれいな」バージョン(評価なし、グローバルなし、正式な引数なし、文字列内の厄介なコードなし)であり、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');

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";
});
于 2010-12-08T16:57:59.153 に答える