有没有JavaScript document.getElementById的速记?或者有没有什么我可以定义的方法?在上重复输入,在上重复输入。
发布于 2011-06-19 04:44:33
var $ = function( id ) { return document.getElementById( id ); };
$( 'someID' )
这里我使用了$
,但是您可以使用任何有效的变量名。
var byId = function( id ) { return document.getElementById( id ); };
byId( 'someID' )
发布于 2011-06-19 11:18:11
要保存额外的字符,可能会污染字符串原型,如下所示:
pollutePrototype(String, '绎', {
configurable: false, // others must fail
get: function() {
return document.getElementById(this);
},
set: function(element) {
element.id = this;
}
});
function pollutePrototype(buildIn, name, descr) {
var oldDescr = Object.getOwnPropertyDescriptor(buildIn.prototype, name);
if (oldDescr && !oldDescr.configurable) {
console.error('Unable to replace ' + buildIn.name + '.prototype.' + name + '!');
} else {
if (oldDescr) {
console.warn('Replacing ' + buildIn.name + '.prototype.' + name + ' might cause unexpected behaviour.');
}
Object.defineProperty(buildIn.prototype, name, descr);
}
}
它可以在某些浏览器中工作,您可以通过以下方式访问元素:
document.body.appendChild(
'footer'.绎 = document.createElement('div')
);
'footer'.绎.textContent = 'btw nice browser :)';
我几乎是随机选择了属性的名称。如果你真的想使用这个速记,我建议你想出一些更容易打字的东西。
发布于 2011-06-19 04:45:48
你可以很容易地自己创建速记:
function getE(id){
return document.getElementById(id);
}
https://stackoverflow.com/questions/6398787
复制相似问题