在每个循环的jQuery中,如何确定所选的$(this)元素是否包含名称为“like”特定值的类。最初hasClass()看起来很有前途,但我不清楚如何使用该函数来处理这个问题。
这是标记。
<div class="command_buttons">
<a class="download_left_button" style="display:none;" href="#"></a>
<a class="bookmark_left_button" href="#"></a>
<a class="search_right_button" href="#"></a>
</div>
这是JavaScript。
findButtonPositionOnCommandBar = function (buttonType) {
/* This function returns 'solo', 'left', 'center', or 'right' text
to tell the button position. The buttonType param should match
a button class prefix like 'bookmark', 'search', or 'download'. */
if ($('.command_buttons').length == 0) { return ''; } // Command bar not found.
// How many visible buttons are on the first command bar found on the page?
var $visibleButtons = $('.command_buttons:first a:visible');
var numberOfButtons = $($visibleButtons).length;
if (numberOfButtons == 0) { return ''; }
if (numberOfButtons == 1) { return 'solo'; }
// This is where I'm having difficulty.
// Find the button with a class name LIKE buttonType_.
buttonSelector = 'class*=' + buttonType + '_';
$($visibleButtons).each(function (index) {
if ($(this).hasClass(buttonSelector)) {
alert('true: ' + index);
} else {
alert('false: ' + index);
}
});
},
例如,如果我们将'bookmark'传递给buttonType参数,则使用上述函数,则需要找到具有'bookmark_left_button'类的锚标记。
我们有各种各样的按钮,可以出现在不同的位置。所以我更愿意找到'bookmark_'而不是为我们可以应用于按钮的所有类的排列编写一个选择(例如bookmark_left_button,bookmark_center_button,bookmark_right_button,download_left_button等)。
感谢您的帮助。
答案 0 :(得分:1)
这样就足够了:
if ($(this).hasClass(buttonType)) {
所以:
.hasClass("bookmark")
你正在尝试进行部分匹配。这表示您的类名未正确设置。
如果你有以下课程:
.bookmark-item {}
.bookmark-header {}
.search-item {}
.search-header {}
并且您希望将应重新组织课程的所有bookmark-*
元素与:
.bookmark.item {}
.bookmark.header {}
.search.item {}
.search.header {}
/* ^- note that there is no space here */
您的HTML将是:<div class="bookmark item"></div>
这允许您使用.hasClass("bookmark")
如果您不清楚CSS语法:
.bookmark .item {}
匹配
<div class="bookmark"><div class="item"></div></div>
尽管
.bookmark.item {}
匹配
<div class="bookmark item"></div>
答案 1 :(得分:1)
试试这个......
buttonSelector = buttonType + '_';
$($visibleButtons).each(function (index) {
if ($(this).attr("class").search(buttonSelector) != -1) {
alert('true: ' + index);
} else {
alert('false: ' + index);
}
});
它只是在class
属性中进行字符串搜索,以查看是否存在buttonType_
。
答案 2 :(得分:0)
使用each()
循环元素时,函数回调使用两个变量:index
,每次传递递增的数字,value
,实际节点本身;所以你需要引用value
。
$($visibleButtons).each(function (index, value) {
if ($(value).hasClass(buttonType)) {
alert('true: ' + index);
} else {
alert('false: ' + index);
}
});