2016-12-02 20 views
0

我知道jQuery是一個JavaScript庫;所以得出結論,必須有可能發明一種jQuery」風格的「」方式來快速訪問document.getElementById(some_id)。但找不到它。請幫幫我。簡單的形式代替document.getElementById,這樣的jQuery方法:「美元符號」

(我的意思是發明了類似$(#some_id),只有通過使用原始JS。)


編輯:更加清晰:

我想使用類似:

$(#some_id); // or anything as brief as this 

而不是:

document.getElementById(some_id); 

但是不是使用jQuery

+0

這真的不清楚你在問什麼。請嘗試澄清(添加一些您正在嘗試完成的示例)。 – Dekel

+0

或者你可以假設這個問題:**如何只使用'jQuery'的那部分來簡化對'document.getElementById()'的訪問?** –

+0

仍然不能真正理解你想要什麼。抱歉。 – Dekel

回答

3

你可以只讓與返回的getElementById的結果,例如短名稱的函數,

function $(id) { 
    return document.getElementById(id); 
} 

然後用它作爲...

var element = $('elementId'); 

我不一定會推薦這種方法,就好像你曾經想要使用jQuery一樣,你會遇到可怕的衝突,但是你可以爲你的函數選擇一個不同的簡稱。

編輯: 這裏實際上沒有必要聲明一個函數,你可以簡單地別名document.getElementById$,因爲它們接受相同的參數。

var $ = document.getElementById; 
+0

這幾乎是100%正確的,除了這隻允許使用「id」。一個努力+ upvoted! – Roberrrt

+0

哦...... OP只希望有'ID'返回,進行 – Roberrrt

0

document.getElementById()是在jQuery中的$('#your_id')。如果這就是你的意思。

1

雖然我很喜歡接受的答案,爲了清楚:我想補充的document.querySelectorALl方法,所以實際上你可以重新創建$(selector)方法

function $(selector) { 
    return document.querySelectorAll(selector); 
} 

請記住,雖然,這要麼返回一個元素或包含元素的NodeList

$('.hello') // returns all elements with class='hello' 
$('#hello') // returns the element with id='hello' 
$('a') // returns all links 
+1

是的。這是一個更好的方式,但[接受的答案](http://stackoverflow.com/questions/40933672/brief-form-instead-document-getelementbyid-such-jquery-method-dollar-sign#answer-40935450)匹配的問題。 –