javascript中链接的问题

时间:2013-07-22 01:15:35

标签: javascript jquery object chaining

我有以下问题,我正在尝试做一个小链接。

(function(window){
window.de=de={}

de.one=function(s){if(s){var y=document.getElementById(s); return y;} return this;}

de.two=function(s2){alert(s2); return this;}

})(window)

这是我尝试的:

de.one("Id").two("Hello!");

但是控制台给了我这个错误:

TypeError:对象#没有方法'two'

3 个答案:

答案 0 :(得分:3)

控制台没有说谎。 HTMLElement没有名为two的方法,因为该方法属于window.de

不要通过添加原型来修改HTMLElement之类的主机对象。它们不是用JavaScript实现的。

编写一个包含你的方法的包装器,有点像jQuery:

(function(window) {
    var de = function(thing) {
        return new de.prototype.init(thing);
    };

    de.prototype = {
        constructor: de,

        init: function(thing) {
            this.thing = thing;
        },

        one: function(other) {
            return de(other);
        }
    };

    de.prototype.init.prototype = de.prototype;

    window.de = de;
})(window);

现在,你可以这样做:

de('foo').one('bar').one('bar').one('baz')

答案 1 :(得分:1)

你不能这样做,问题出在de.one(),你有2种不同的返回值类型。

“返回y”并返回“this”。如果你想连锁,你必须“这个”。

答案 2 :(得分:1)

给你一个想法:

<强> LIVE DEMO

(function(window){

var myLibrary = (function( s ) {
  var d = document,
      e = d.getElementById( s ),
      methods = {
        one : function(val){
            alert(val);
            return this; // maintain chainability
        }, 
        two : function(val){
            alert(val);
            return this; // maintain chainability
        },
        css : function( property, val){
            if(!val && typeof property == "object" ){ // styles in Object notation
                for(var key in property){
                    e.style[key] = property[key];
                }
            }else{ // Comma separated: property, value
                e.style[property] = val || undefined;
            }
            return this;    
        }
    };
    return methods;

});
window.myLibrary = window.de = myLibrary; // Make Window accept "de" as "myLib" alias.   

})(window);

de("Id").one("UGA!!!").two("yoo").css({color:"red", background:"gold"});

考虑到你有类似的东西:

 <div id="Id">Some element</div>