在 jQuery 的每个循环中,我如何确定选定的 $(this) 元素是否包含一个名称“喜欢”特定值的类。最初 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等)。
谢谢你的帮助。