问题描述
在不使用任何开源框架(jQuery的,等等):),在JavaScript中,什么是搜索的任何控件属性的最有效方式。 (任何新/旧浏览器)
这是我种下的格局。有没有更好的方法或任何更好的 getElementByAttribute()
的方法?谢谢!
例如
<输入类型=按钮ID =B1值=继续A1 =东西/>
<输入类型=文本ID =T1A1 =something1/><脚本>
VAR attrToFind =的东西; something1VAR elems =的document.all?的document.all:document.getElementByTagName(*);
//假设elems总是工作
对于(VAR I = 0; I< elems.length;我++)
{
变种ATT = elems [I] .getAttribute(A1);
如果(typeof运算ATT ==字符串)
{
如果(att.indexOf(attrToFind)-1个)
... // ATTR你找哪个,创建数组,保存价值的搜索等。
}
}
< / SCRIPT>
访问一个的HTMLCollection
(由 getElement [S]返回由*
函数)是的慢相比,访问数组,因为的HTMLCollection
必须的文件在任何时候(匹配它的住的)。
由于这个原因,最好创建从的HTMLCollection
数组和遍历的。
这是一个比较优化的:
VAR attrToFind =的东西; something1
elems =的document.all?的document.all:document.getElementByTagName('*'),
我,ATTR;//在Firefox;不知道其他浏览器和发动机。
elems = Array.prototype.slice.call(elems);I = elems.length;而(ⅰ - 大于0){
ATTR = elems [I] .getAttribute('A1'); //你确定你想要的indexOf?
// ATT === attrToFind可能更快,因为它需要一个更小的比较。
如果(typeof运算ATT =='串'|| att.indexOf(attrToFind)LT;!0){
继续;
} // 做东西。
}
Without using any open source framework (jQuery, etc.) :), in JavaScript, what's the most efficient way to search for attributes in any controls. (Any old/new browsers)
This is the pattern I'm kind of following. Is there any better way or any better getElementByAttribute()
method? Thanks!
e.g
<input type="button" id="b1" value="Continue" a1="something" />
<input type="text" id="t1" a1="something1" />
<script>
var attrToFind = "something;something1";
var elems = document.all ? document.all : document.getElementByTagName("*");
//assume elems work always
for(var i = 0 ; i < elems.length; i++)
{
var att = elems[i].getAttribute("a1");
if (typeof att == "string")
{
if (att.indexOf(attrToFind) > -1)
... //search which attr you find, create array, save value, etc.
}
}
</script>
Accessing an HTMLCollection
(returned by getElement[s]By*
functions) is slow in comparison to accessing arrays because an HTMLCollection
must match the document at all times (it is live).
For this reason, it's best to create an array from the HTMLCollection
and iterate over that.
This is a bit more optimized for speed:
var attrToFind = "something;something1",
elems = document.all ? document.all : document.getElementByTagName('*'),
i, attr;
// Works in Firefox; not sure about other browsers and engines.
elems = Array.prototype.slice.call(elems);
i = elems.length;
while(i --> 0) {
attr = elems[i].getAttribute('a1');
// Are you sure you want indexOf?
// att === attrToFind may be faster, as it requires one less comparison.
if(typeof att !== 'string' || att.indexOf(attrToFind) < 0) {
continue;
}
// Do stuff.
}
这篇关于在JavaScript中搜索属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!