document.getElementById()的简写形式,如jQuery"dollar-sign"方法:$()
Brief form of document.getElementById(), such as jQuery "dollar-sign" method: $()
我想使用类似的东西:
$('#some_id') // or anything as brief as this
而不是:
document.getElementById('some_id')
但是不是通过使用jQuery
!
document.getElementById()
是 jQuery 中的 $('#your_id')
。如果这就是你的意思。
您可以只创建一个短名称的函数,returns getElementById 的结果,例如,
function $(id) {
return document.getElementById(id);
}
然后将其用作...
var element = $('elementId');
我不一定会推荐这种方法,因为如果你真的想使用 jQuery 你会遇到可怕的冲突,但你可以为你的函数选择一个不同的短名称。
编辑:
实际上没有必要在这里声明一个函数,你可以简单地将 document.getElementById
别名为 $
因为它们接受相同的参数。
var $ = document.getElementById;
虽然我喜欢接受的答案,但为了清楚起见:我想添加 document.querySelectorALl
方法,这样您实际上可以重新创建 $(selector)
方法
function $(selector) {
return document.querySelectorAll(selector);
}
请记住,这个 returns 要么是一个元素,要么是一个包含元素的 NodeList
$('.hello') // returns all elements with class='hello'
$('#hello') // returns the element with id='hello'
$('a') // returns all links
定义:
const $ = document.querySelector.bind(document)
我想使用类似的东西:
$('#some_id') // or anything as brief as this
而不是:
document.getElementById('some_id')
但是不是通过使用jQuery
!
document.getElementById()
是 jQuery 中的 $('#your_id')
。如果这就是你的意思。
您可以只创建一个短名称的函数,returns getElementById 的结果,例如,
function $(id) {
return document.getElementById(id);
}
然后将其用作...
var element = $('elementId');
我不一定会推荐这种方法,因为如果你真的想使用 jQuery 你会遇到可怕的冲突,但你可以为你的函数选择一个不同的短名称。
编辑:
实际上没有必要在这里声明一个函数,你可以简单地将 document.getElementById
别名为 $
因为它们接受相同的参数。
var $ = document.getElementById;
虽然我喜欢接受的答案,但为了清楚起见:我想添加 document.querySelectorALl
方法,这样您实际上可以重新创建 $(selector)
方法
function $(selector) {
return document.querySelectorAll(selector);
}
请记住,这个 returns 要么是一个元素,要么是一个包含元素的 NodeList
$('.hello') // returns all elements with class='hello'
$('#hello') // returns the element with id='hello'
$('a') // returns all links
定义:
const $ = document.querySelector.bind(document)