-1

すべてのメソッドを関数でオブジェクトに自動的にラップしたいと思います。今のところ、私はそれを1つずつ行う方法しか知りません:

jsfiddle: http://jsfiddle.net/4VuE7/

コード:

<div style=white-space:pre>
<i>foo bar lorem ipsum</i>
<i>foo bar lorem ipsum</i>
<i>foo bar lorem ipsum</i>
<i>foo bar lorem ipsum</i>
<i>foo bar lorem ipsum</i>
<i>foo bar lorem ipsum</i>
</div>​
<script>

//method that only works on elements:
Element.prototype.css = function(a,i,n){for(n in''+a===a||a)this.style[n]=a[n];return i||n?(this.style[a]=i,this):getComputedStyle(this)[a]};

//put a wrapper around it that makes it work with nodelists
NodeList.prototype.css = function(a,i){for(var n in this)this[n].css(a,i)};

//put a wrapper around it so it works with a selector in a string
String.prototype.css = function(a,i){document.querySelectorAll(this).css(a,i)}​;

//use the method:

"div>i".css("color","red")​;​

</script>

オブジェクト内のすべてのメソッドに対してこれを自動的に行いたいと思います。(単一の関数がすべてのメソッドを自動的にラップします)

免責事項: 自分が何をしているのか本当にわからない限り、dom をいじらないでください! (おそらくしないでしょう!) この例は、デモンストレーションのみを目的としています。

4

1 に答える 1

0

私はそれを行う方法を見つけました!: http://jsfiddle.net/4VuE7/3/

Element.prototype.css = function(a,i,n){
for(n in''+a===a||a)this.style[n]=a[n];return i||n?(this.style[a]=i,this):getComputedStyle(this)[a]};

Object.getOwnPropertyNames(Element.prototype).forEach(function(a){

    NodeList.prototype[a]=function(){for(var n in this)this[n][a].apply(this[n],arguments)}

    String.prototype[a]=function(){document.querySelectorAll(this)[a].apply(document.querySelectorAll(this),arguments)}

});


"div>i".css("color","red");​
于 2012-05-31T16:09:28.013 に答える