我有一个jQuery代码,它正在计算一些div,其中找到某些早餐板,如下所示
var board_bb1 = $('div[data-board="Bed And Breakfast"]').length;
var board_bb2 = $('div[data-board="Breakfast"]').length;
var board_bb3 = $('div[data-board="Breakfast Buffet"]').length;
var board_bb4 = $('div[data-board="Breakfast (Full Breakfast)"]').length;
var board_bb5 = $('div[data-board="Continental Breakfast"]').length;
var board_bb8 = $('div[data-board="Bed and Breakfast"]').length;
var board_bb6 = $('div[data-board="Full Breakfast"]').length;
var board_bb7 = $('div[data-board="Breakfast (Continental Breakfast)"]').length;
var board_bb = board_bb1 + board_bb2 + board_bb3 + board_bb4 + board_bb5 + board_bb6 + board_bb7 + board_bb8;
数据板的属性来自API服务,有时早餐有时是早餐,住宿加早餐等。 有没有办法简单地上面的代码来计算所有在数据板中都有单词Breakfast的div?
答案 0 :(得分:5)
$("div[data-board*='Breakfast']").length
*=
部分将查找包含单词breakfast.
IF 您没有在项目中使用jQuery,在现代浏览器中,这将适用于:
document.querySelectorAll("div[data-board*='Breakfast']").length;
完成它:一个跨浏览器的解决方案,可以一直回到IE5.5
var allDivs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0, i < allDivs.length; i++)
{
if (allDivs[i].getAttribute("data-board") && allDivs[i].getAttribute("data-board").match(/Breakfast/) )
{
count++;
}
}
此后count
将返回Breakfast
属性中包含单词data-board
的div数量
答案 1 :(得分:3)
您可以使用~
运算符
$("div[data-board~='Breakfast']").length