听起来很简单,是吧。我找到了很多答案,但都使用 jQuery 或 ProtoType。我想要纯 JavaScript。它不应该那么难,但 JavaScript 不是我的事;没有中央文档意味着搜索年龄并找不到我想要的东西。
考虑以下 HTML 代码片段:
<div class="central_0"> .. </div>
<div class="central_1"> .. </div>
<div class="central_2"> .. </div>
现在我想使用 JavaScript 来处理这些 DIV。
function processDivElements()
{
// search for relevant DIV classes
var divArray = document.getElementsByClass.regex('/^central_.*$/');
// do stuff with the DIV elements found
foreach (divArray as divElement)
{
divElement.style.background = '#f00';
};
}
谁能帮我把它翻译成正确的普通 JavaScript?我使用类,而不是 ID。我更喜欢使用正则表达式。
最佳答案
jQuery 解决方案非常好:
var $divs = $('div[class^="central_"]');
如果你只想支持更新的浏览器,你可以使用document.querySelectorAll()
做本质上相同的事情:
var divs = document.querySelectorAll('div[class^="central_"]');
如果你想支持旧的浏览器,代码会变得很糟糕:
var all_divs = document.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < all_divs.length; i++) {
var div = all_divs[i];
if (div.className.match(/^central_\d+$/) {
divs.push(div);
}
}
还有:
I use classes, not IDs. I prefer using a regular expression.
您的类是独一无二的,并且确实像 ID 一样发挥作用,这并不是类的真正用途。改为像这样构建您的 HTML:
<div id="central_0" class="central">...</div>
<div id="central_1" class="central">...</div>
<div id="central_2" class="central">...</div>
现在,JavaScript 变得更简单了:
var $divs = $('.central'); // jQuery
var divs = document.querySelectorAll('.central'); // Newer browsers
var divs = document.getElementsByClassName('central'); // Older browsers
关于javascript - 使用正则表达式搜索 div 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13775282/