开发者

how to make a class accept a method without specifying the method in advance?

If i have something like this :

function foo(class){
    for(i=0; i<(class.length);i++){
       return document.getElementsByClassName(class)[i];
    }
}

And now i want to do something like this:

 foo("someclass").innerHTML="something";

it will do it only for the first element and i understand why this happens and how to make it work correctly, but how can i make the function get other methods without telling it in the loop exactly what to do,like this

   foo("someclass").innerHTML="something";//this to put something inside the element
   foo("someclass").style.backgroundColor="#000");// and this to work also

So,if its possible,how can i make the function do this without putting these methods in the foo function loop? Is there a way to 开发者_如何学Cput these methods in a variable like this

  function foo(class).variableMethod{
for(i=0; i<(class.length);i++){
   document.getElementsByClassName(class)[i].variableMethod;
}

}

Is this possible?


You can pass a function to foo(), and have foo() call that function with each matched element:

function foo(className, func)
{
    var elements = document.getElementsByClassName(className);
    for (var i = 0; i < elements.length; ++i) {
        func(elements[i]);
    }
}

Now you can do something like:

foo("someclass", function(element) {
    element.innerHTML = "something";
    element.style.backgroundColor = "#000";
});


Just to add to the other great answers here, one thing you could do is create on override method called innerHtml. You could then have innerHtml check for a collection as well as a single instance and opperate as required.

UPDATE

Here's a quick example of method chaining. Here I basically obtain a collection of elements based on tag name and set their value using a val() method that I created using the Javascript prototype object.

function Foo(tagName)
{
    this.collection = document.getElementsByTagName(tagName);
    return this;
}

Foo.prototype.val= function(value){

   for(var i = 0; i < this.collection.length; i++)
   {
       this.collection[i].innerHTML = value;
   }
}


var x = new Foo("li").val("Hello World");

You can see a working demo of this here: http://jsfiddle.net/E48ym/1/


Frédéric Hamidi's answer will do what you want I think, but you could also use a framework like jQuery - this is the kind of thing it was designed for. So you could do:

$('.className').text('something');

to set the text of all elements with a class of className to something, or

$('.className').css('background-color', '#000');

to change the background color of all elements with a class of className.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜