简体   繁体   English

通用字符串选择器的Javascript吗?

[英]Universal String selector for Javascript?

I have something like 我有类似的东西

x.getElementById("foo" + rowIndex);

There are a couple of cases that have some other string before the "foo" in the ID, and my question is if there are any replacements (like the "%" in SQL) that I could use to add something else to the "foo" like 在几种情况下,ID中的“ foo”之前还有一些其他字符串,我的问题是是否有任何替换(例如SQL中的“%”)可以用来向“ foo”添加其他内容“ 喜欢

x.getElementById("%foo" + rowIndex);

If you use querySelector instead of getElementById , you can pass a selector string that selects an ID which ends with the substring you want, for example: 如果使用querySelector而不是getElementById ,则可以传递选择器字符串,该选择器字符串选择所需子字符串结尾的ID,例如:

x.querySelector('[id$="foo' + rowIndex + '"]');

 const rowIndex = 3; console.log(document.querySelector('[id$="foo' + rowIndex + '"]')); 
 <div id="barfoo3">text</div> 

(of course, if you want to select all elements whose ID ends with that, use querySelectorAll instead of querySelector ) (当然,如果要选择所有以ID结尾的元素,请使用querySelectorAll而不是querySelector

That said, note that such dynamic IDs are somewhat of a code smell - you might consider if there are more elegant alternative methods. 就是说,请注意,这样的动态ID有点像代码的味道-您可以考虑是否有更优雅的替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM