2014-05-22 120 views
-2

重要注意事項所以人們不會被抓到(就像我做的那樣):這可能看起來像jQuery,但它不是
老實說,我應該早知道。除了jQuery以外,我使用$。好吧。學過的知識! 〜Niet的黑暗ABSOL無法運行功能

代碼:

(HTML):

<html> 
    <head> 
     <script src="selector.js"></script> 
    </head> 
    <body> 
     <label id="id">A label</label> 
     <script> 
     $("label #id").clicked(function(){ 
      alert("ASDASD"); 
     }); 
     </script> 
    </body> 
</html> 

(JS):

/* 
    NAME : SELECTOR.JS 
*/ 

function $(attr){ 

    // Removed space in front of the variable 
    while(attr.charAt(0) == " "){ 
     attr = attr.substr(1); 
     if(attr == ""){ 
      return 0; 
     } 
    } 

    // Completed the query 
    if(attr.length > 1){ 
     return Array.prototype.slice.call(document.querySelectorAll(attr)); 
    }else{ 
     if(attr.length == 1){ 
      return new Object(document.querySelector(attr)); 
     }else{ 
      return null; 
     } 
    } 
} 

Object.prototype.clicked = function(script){ 
    if(typeof(this) == "object"){ 
     if(this.constructor == Array){ 
      for(var i = 0; i < this.length; i++){ 
       this[i].onclick = script; 
      } 
     }else{ 
      if(this.constructor == Object){ 
       console.log("SINGLE OBJECT : " + this); 
       console.log("SINGLE OBJECT : ONCLICK : " + this); 
       this.onclick = script; 
      }else{ 
       console.log("ERROR : this.constructor is not 'Object' or 'Array'."); 
       return null; 
      } 
     } 
    }else{ 
     console.log("ERROR : typeof(this) is not 'Object'."); 
     return null; 
    } 

    return this; 
}; 

當我點擊標籤,我不能得到的警告框看到。 我該怎麼辦?文件名是selector.js,用於js文件。 我需要運行的功能。請幫忙!

我認爲這是最小化的代碼。

+1

你的選擇是尋找「與ID元素'id' *這是一個''

+0

gshhh .... downvoters今天很忙:-) –

+0

Downvoters投我的正確答案。 Argh –

回答

1

該空間是錯誤的,而不是$("label #id")它需要是$("label#id")。在label#id之間的空間,您正在尋找label的內容,使用id="id",沒有找到空格,label使用id="id"

+2

實際上,它「需要」是$(「#id」)。 ID是獨一無二的,並且進一步限定它們是多餘的。 –

+0

這就是我期待的。謝謝! –

-1

功能

.clicked() 
您使用

,不是一個有效的jQuery函數。你正在尋找的一個是:

$("#target").click(function() { 
     alert("Handler for .click() called."); 
}); 

在這裏看到:

http://api.jquery.com/click/