getElementById 的 JavaScript 简写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6398787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:33:38  来源:igfitidea点击:

Javascript Shorthand for getElementById

javascript

提问by Fox Wilson

Is there any shorthand for the JavaScript document.getElementById? Or is there any way I can define one? It gets repetitive retyping that overand over.

JavaScript document.getElementById 有简写吗?或者有什么方法可以定义一个?它得到重复重复输入是超过

回答by user113716

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

$( 'someID' )

Here I used $, but you can use any valid variable name.

我在这里使用了$,但您可以使用任何有效的变量名。

var byId = function( id ) { return document.getElementById( id ); };

byId( 'someID' )

回答by Robert

To save an extra character you could pollute the String prototype like this:

要保存额外的字符,您可以像这样污染 String 原型:

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);
    }
}

It works in some browsers and you can access elements this way:

它适用于某些浏览器,您可以通过以下方式访问元素:

document.body.appendChild(
    'footer'.绎 = document.createElement('div')
);
'footer'.绎.textContent = 'btw nice browser :)';

I have chosen the name of the property almost randomly. If you actually wanted to use this shorthand I would suggest coming up with something easier to type.

我几乎是随机选择了房产的名称。如果你真的想使用这个速记,我建议你想出一些更容易输入的东西。

回答by Sarfraz

You can easily create shorthand easily yourself:

您可以轻松地自己轻松创建速记:

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

回答by Pablo Fernandez

A quick alternative to contribute:

贡献的快速替代方案:

HTMLDocument.prototype.e = document.getElementById

Then just do:

然后就这样做:

document.e('id');

There's a catch, it doesn't work in browsers that don't let you extend prototypes (e.g. IE6).

有一个问题,它在不允许您扩展原型的浏览器(例如 IE6)中不起作用。

回答by JiminP

(Shorthand for not only getting element by ID, but also getting element by class :P)

(不仅可以通过 ID 获取元素,还可以通过类获取元素的简写:P)

I use something like

我使用类似的东西

function _(s){
    if(s.charAt(0)=='#')return [document.getElementById(s.slice(1))];
    else if(s.charAt(0)=='.'){
        var b=[],a=document.getElementsByTagName("*");
        for(i=0;i<a.length;i++)if(a[i].className.split(' ').indexOf(s.slice(1))>=0)b.push(a[i]);
        return b;
    }
}

Usage : _(".test")returns all elements with class name test, and _("#blah")returns an element with id blah.

用法:_(".test")返回所有具有类名的元素test,并_("#blah")返回一个具有 id 的元素blah

回答by im_benton

id's are saved to the window.

id 被保存到window.

HTML

HTML

 <div id='logo'>logo</div>

JS

JS

logo.innerHTML;

is the same as writing:

与写作相同:

document.getElementById( 'logo' ).innerHtml;

I don't suggest using the former method as it is not common practice.

我不建议使用前一种方法,因为它不是常见的做法。

回答by Kon

There are several good answers here and several are dancing around jQuery-like syntax, but not one mentions actually using jQuery. If you're not against trying it, check out jQuery. It let's you select elements super easy like this..

这里有几个很好的答案,有几个围绕类似 jQuery 的语法跳舞,但没有一个提到实际使用 jQuery。如果您不反对尝试,请查看jQuery。它让你像这样选择元素超级简单..

By ID:

通过身

$('#elementId')

By CSS class:

通过 CSS 类

$('.className')

By element type:

按元素类型

$('a')  // all anchors on page 
$('inputs')  // all inputs on page 
$('p a')  // all anchors within paragaphs on page 

回答by genesis

<script>
var _ = function(eId)
{
    return getElementById(eId);
}
</script>

<script>
var myDiv = _('id');
</script>

回答by Alnitak

There's none built-in.

没有内置的。

If you don't mind polluting the global namespace, why not:

如果您不介意污染全局命名空间,为什么不:

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

EDIT - I changed the function name to be something unusual, but shortand not otherwise clashing with jQuery or anything else that uses a bare $sign.

编辑 - 我将函数名称更改为不寻常的名称,但很短,并且不会与 jQuery 或其他任何使用裸$符号的东西发生冲突。

回答by Robert

Yes, it gets repetitive to use the same function overand overeach time with a different argument:

是的,它会重复使用相同的功能,并用不同的参数,每次:

var myImage = document.getElementById("myImage");
var myDiv = document.getElementById("myDiv");

So a nice thing would be a function that takes all those arguments at the same time:

所以一件好事是一个同时接受所有这些参数的函数:

function getElementsByIds(/* id1, id2, id3, ... */) {
    var elements = {};
    for (var i = 0; i < arguments.length; i++) {
        elements[arguments[i]] = document.getElementById(arguments[i]);
    }
    return elements;
}

Then you would have references to all your elements stored in one object:

然后,您将引用存储在一个对象中的所有元素:

var el = getElementsByIds("myImage", "myDiv");
el.myImage.src = "test.gif";

But you would still have to list all those ids.

但是您仍然必须列出所有这些 id。

You could simplify it even more if you want allelements with ids:

如果您想要所有带有 id 的元素,您可以进一步简化它:

function getElementsWithIds() {
    var elements = {};
    var elementList = document.querySelectorAll("[id]");
    for (var i = 0; i < elementList.length; i++) {
        elements[elementList[i].id] = elementList[i];
    }
    return elements;
}

But it would be pretty expensive to call this function if you have many elements.

但是如果你有很多元素,调用这个函数会非常昂贵。



So, theoretically, if you would use the withkeyword you could write code like this:

因此,理论上,如果您使用with关键字,您可以编写如下代码:

with (getElementsByIds('myButton', 'myImage', 'myTextbox')) {
    myButton.onclick = function() {
        myImage.src = myTextbox.value;
    };
}

But I don't want to promote the use of with. Probably there's a better way to do it.

但我不想推广使用with. 可能有更好的方法来做到这一点。