2013-10-23 71 views
0

再次處理我的框架。想要創建一種方法來閃爍一個元素。我需要在方法內設置間隔。所以我想這可能工作:方法內的設置間隔

var optionalSelector = "$"; 

(function() { 
    (this[arguments[0]] = function constructor(input) { 
     if (!(this instanceof constructor)) { return new constructor(input); } 
     this.elm = document.getElementById(input); 
    }).prototype = { 
     blink:  function() { 
         function changeDisplay() { 
          if (this.elm.style.display != "none") { 
           this.elm.style.display = "none"; 
          } else { 
           this.elm.style.display = "block"; 
          } 
         } 
         setInterval(changeDisplay, 1000); 
        }, 
    }; 
})(optionalSelector); 

並調用方法$("anElmId").blink();

但事實並非如此。該方法內的另一個函數,也有一個間隔。我想這兩個東西搞砸了。像它不承認this.elm。由於我是新手,我無法找出解決這個問題的方法。有任何想法嗎?

Fiddle

回答

0

你應該試着在你的代碼中的console.log語句。在Chrome或Firefox中(最好安裝Firebug插件)時,可以按F12打開控制檯並查看日誌輸出。

console.log(this) 

在changeDisplay就會發現,this最有可能的是Window。要理解爲什麼你必須瞭解什麼是this代表JavaScript。我喜歡稱它爲調用 對象的函數,因爲它最準確地描述它(在我看來)。有關更多詳細信息,請參閱here

var optionalSelector = "$"; 
window[optionalSelector] = function constructor(input) { 
    if (!(this instanceof constructor)) { 
    return new constructor(input); 
    } 
    this.elm = document.getElementById(input); 
    this.intervalid = 0; 
    this.timeoutid = 0; 
}; 
window[optionalSelector].prototype.blink = 
    function(interval, timeout) { 
    this.intervalid = setInterval(this._callbacks. 
     changeDisplay(this.elm), interval); 
    this.timeoutid=setTimeout(this._callbacks. 
     cancelInterval(this.intervalid),timeout); 
    return this; 
}; 
window[optionalSelector].prototype.cancel = function() { 
    clearTimeout(this.timeoutid); 
    clearInterval(this.intervalid); 
    return this; 
}; 
// I like to have callback functions (closures) in it's own 
// scope so you can better control what variables 
// are passed to it 
window[optionalSelector].prototype._callbacks = { 
    changeDisplay: function(elm) { 
    return function() { 
     if (elm.style.display !== "none") { 
     elm.style.display = "none"; 
     } else { 
     elm.style.display = "block"; 
     } 
    }; 
    }, 
    cancelInterval:function(intervalid){ 
    return function(){ 
     clearInterval(intervalid); 
    }; 
    } 
}; 

var myBlinker = window[optionalSelector] 
    ("hplogo").blink(200, 2000); 
//cancel it 
myBlinker.cancel(); 
//blink something else for 2 seconds 
window[optionalSelector]("gbqfba").blink(200, 2000); 

去google.com按F12並運行上面的代碼。它應該工作。更多關於原型屬性和實例屬性here之間的區別。

+0

好的。最終代碼如下所示:[Fiddle](http://jsfiddle.net/Apazm/3/)。它似乎工作。雖然我有一個問題。你提到關於清除間隔。我怎樣才能做到這一點?例如使用小提琴中的按鈕。 – akinuri

+0

@akinuri我重新格式化了你的代碼,因爲它不必要地爲'(function(){...}())中定義的每個函數創建一個閉包'如果你想將整個東西包裝在自調函數你仍然可以這樣做。 – HMR

+0

我認爲這段代碼中有些東西需要處理=)但是由於實際問題已經解決,我會接受這個。 – akinuri