0

在 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等)。

谢谢你的帮助。

4

3 回答 3

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>
于 2013-09-19T16:18:23.270 回答
1

尝试这个...

buttonSelector = buttonType + '_'; 
$($visibleButtons).each(function (index) {
    if ($(this).attr("class").search(buttonSelector) != -1) {
        alert('true: ' + index);
    } else {
        alert('false: ' + index);
    }
});

它只是在class属性中进行字符串搜索以查看是否buttonType_存在。

于 2013-09-19T16:20:52.623 回答
0

当使用 循环遍历元素each()时,函数回调使用两个变量:index,一个随着每次传递递增的数字,以及value,实际节点本身;所以你需要参考value.

$($visibleButtons).each(function (index, value) {
     if ($(value).hasClass(buttonType)) {
        alert('true: ' + index);
     } else {
        alert('false: ' + index);
     }
  });
于 2013-09-19T16:18:34.657 回答