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

标签 javascript jquery

在 jQuery Each 循环中,如何确定选定的 $(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”类的 anchor 标记。

我们有多种可以出现在不同位置的按钮。因此,我更愿意找到“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_ 是否存在。

关于javascript - 确定 jQuery 每个循环中的 $(this) 元素是否像字符串一样具有Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18899961/

相关文章:

javascript - 使用 HTML5 和 JavaScript 修改本地文件

jquery - 添加 return true 到 jquery 循环的下一个/上一个按钮

javascript - 如何根据购物者在自定义字段中输入的字符数动态更改产品价格?

javascript - GooglemapV3 infowindow closeclick 事件未触发

javascript - 这个设计叫什么?

javascript - 定期更新 Angular2 中的 Observable 值

javascript - 我怎样才能做一个精确图像形状的鼠标悬停?

javascript - 使用 php 从 MySQL 表中选择并显示

php - AJAX 发布值在 PHP 中被接收为空

javascript - jQuery 图像 slider 封面图像定位问题