JQuery - 如何为每个嵌套获取此内容

  • 本文关键字:获取 嵌套 JQuery jquery
  • 更新时间 :
  • 英文 :


我有内在的喜欢

$('a[id^="Page"]').each(function () {
   if ($(this).attr("id") == pageId) {
     $('[id="' + pageId + '"]"').each(function () {
       // code here
      });
  }
});

如何访问当前元素,因为它来自以前的each this

谢谢!

您可以使用回调的第二个参数来获取元素,如下所示:

 $('a[id^="Page"]').each(function (index, element) {
         if ($(element).attr("id") == pageId) {
                  $('[id="' + pageId + '"]"').each(function (j, pageElment) {
                       console.log(element);
                       console.log(pageElment);
                  });
         }
 });

首先,您可以使用以下回调签名来消除this的使用:

.each(function(outerIndex, outerElement) {
    .each(function(innerIndex, innerElement) {
        // Do stuff with outerElement...
    });
});

这比使用this重言式更具可读性。

但是,在您的示例中,根本不需要在第一个each(...中使用第二个each(...,因为您要查找确切的 id。如果你提前知道pageId - 你不需要任何each(....相反,只需使用 id 选择器:

$('#' + pageId).// Do your stuff
默认情况下

this是指调用函数的上下文。当您对一个或多个元素调用.each时,函数内部this将始终引用当前元素。

只需将this保存到变量中,然后就可以使用它:

$('a[id^="Page"]').each(function () {
     var $that = $(this);
     if ($that.attr("id") == pageId) {
          $('[id="' + pageId + '"]"').each(function () {
              console.log($that.data('val') === $(this).data('val'));
          });
     }
});

如果您有身份证件作为号码(例如 id="12345" ),而不是阅读此内容

最新更新