确定 jQuery 中每个循环中的 $(this) 元素是否像字符串一样具有类

Determine if $(this) element within jQuery each loop hasClass like a string

本文关键字:字符串 一样 是否 元素 循环 jQuery 确定 this      更新时间:2023-09-26

在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);
     }
  });
},

例如,使用上述函数,如果我们将"书签"传递给 buttonType 参数,那么它需要找到具有"bookmark_left_button"类的锚标签。

我们有各种各样的按钮可以出现在不同的位置。 所以我宁愿找到"bookmark_",而不是为我们可以应用于按钮的所有类排列(即bookmark_left_button、bookmark_center_button、bookmark_right_button、download_left_button等)编写一个选择。

感谢您的帮助。

试试这个...

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

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

只需执行以下操作:

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>
当使用

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

$($visibleButtons).each(function (index, value) {
     if ($(value).hasClass(buttonType)) {
        alert('true: ' + index);
     } else {
        alert('false: ' + index);
     }
  });
相关文章: