ID 以纯 Javascript 结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5248703/
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
ID Ends With in pure Javascript
提问by Brian Genisio
I am working in a Javascript library that brings in jQuery for one thing: an "ends with" selector. It looks like this:
我在一个 Javascript 库中工作,它为一件事引入了 jQuery:“以”选择器。它看起来像这样:
$('[id$=foo]')
It will find the elements in which the idends with "foo".
它将找到id以“foo”结尾的元素。
I am looking to do this without jQuery (straight JavaScript). How might you go about this? I'd also like it to be as efficient as reasonably possible.
我希望在没有 jQuery(直接 JavaScript)的情况下做到这一点。你会怎么做?我也希望它尽可能高效。
回答by pimvdb
Use querySelectorAll, not available in all browsers (like IE 5/6/7/8) though. It basically works like jQuery:
使用querySelectorAll,但并非在所有浏览器(如 IE 5/6/7/8)中可用。它基本上像 jQuery 一样工作:
console.log(document.querySelectorAll("[id$=foo]"));
回答by ThiefMaster
You will need to iterate over all elements on the page and then use string functions to test it. The only optimizations I can think of is changing the starting point - i.e. not document.bodybut some other element where you know your element will be a child of - or you could use document.getElementsByTagName()to get an element list if you know the tag name of the elements.
您将需要遍历页面上的所有元素,然后使用字符串函数对其进行测试。我能想到的唯一优化是改变起点 - 即不是,document.body而是其他一些你知道你的元素将是其子元素的元素 - 或者document.getElementsByTagName()如果你知道元素的标签名称,你可以使用它来获取元素列表。
However, your task would be mucheasier if you could use some 3rd-party-javascript, e.g. Sizzle(4k minified, the same selector engine jQuery uses).
但是,如果您可以使用一些 3rd-party-javascript,例如Sizzle(4k 缩小,jQuery 使用的相同选择器引擎),您的任务会容易得多。
回答by Brian Genisio
So, using everything that was said, I put together this code. Assuming my elements are all inputs, then the following code is probably the best I am going to get?
所以,使用所说的一切,我把这段代码放在一起。假设我的元素都是inputs,那么下面的代码可能是我得到的最好的代码?
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
function getInputsThatEndWith(text) {
var result = new Array();
var inputs = document.getElementsByTagName("input");
for(var i=0; i < inputs.length; i++) {
if(inputs[i].id.endsWith(text))
result.push(inputs[i]);
}
return result;
}
I put it on JsFiddle: http://jsfiddle.net/MF29n/1/
我把它放在 JsFiddle 上:http: //jsfiddle.net/MF29n/1/
回答by zzzzBov
@ThiefMaster touched on how you can do the check, but here's the actual code:
@ThiefMaster 谈到了如何进行检查,但这是实际代码:
function idEndsWith(str)
{
if (document.querySelectorAll)
{
return document.querySelectorAll('[id$="'+str+'"]');
}
else
{
var all,
elements = [],
i,
len,
regex;
all = document.getElementsByTagName('*');
len = all.length;
regex = new RegExp(str+'$');
for (i = 0; i < len; i++)
{
if (regex.test(all[i].id))
{
elements.push(all[i]);
}
}
return elements;
}
}
This can be enhanced in a number of ways. It currently iterates through the entiredom, but would be more efficient if it had a context:
这可以通过多种方式增强。它目前遍历整个dom,但如果它有上下文会更有效:
function idEndsWith(str, context)
{
if (!context)
{
context = document;
}
...CODE... //replace all occurrences of "document" with "context"
}
There is no validation/escaping on the strvariable in this function, the assumption is that it'll only receive a string of chars.
str此函数中的变量没有验证/转义,假设它只会接收一串字符。
回答by Matt Ball
Suggested changes to your answer:
对您的答案的建议更改:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\(){}-])/g, "\");
}; // from https://stackoverflow.com/questions/494035/#494122
String.prototype.endsWith = function(suffix) {
return !!this.match(new RegExp(RegExp.quote(suffix) + '$'));
};
function getInputsThatEndWith(text) {
var results = [],
inputs = document.getElementsByTagName("input"),
numInputs = inputs.length,
input;
for(var i=0; i < numInputs; i++) {
var input = inputs[i];
if(input.id.endsWith(text)) results.push(input);
}
return results;
}
http://jsfiddle.net/mattball/yJjDV/
http://jsfiddle.net/mattball/yJjDV/
Implementing String.endsWithusing a regex instead of indexOf()is mostly a matter of preference, but I figured it was worth including for variety. If you aren't concerned about escaping special characters in the suffix, you can remove the RegExp.quote()bit, and just usenew RegExp(suffix + '$').
String.endsWith使用正则表达式而不是实现indexOf()主要是偏好问题,但我认为值得将其包括在内。如果您不担心在后缀中转义特殊字符,则可以删除该RegExp.quote()位,只需使用new RegExp(suffix + '$').
回答by DhruvPathak
If you know the type of DOM elements you are targeting,
then get a list of references to them using getElementsByTagName, and then iterate over them.
如果您知道要定位的 DOM 元素的类型,则使用 获取对它们的引用列表getElementsByTagName,然后遍历它们。
You can use this optimization to fasten the iterations:
您可以使用此优化来加快迭代:
ignore the elements not having id.
target the nearest known parent of elements you want to seek, lets say your element is inside a div with id='myContainer', then you can get a restricted subset using
document.getElementById('myContainer').getElementsByTagName('*'), and then iterate over them.
忽略没有 id 的元素。
定位您要查找的元素的最近的已知父元素,假设您的元素位于 id='myContainer' 的 div 内,然后您可以使用 获取受限子集
document.getElementById('myContainer').getElementsByTagName('*'),然后迭代它们。

