【问题标题】:Iterate over select DOM elements迭代选择的 DOM 元素
【发布时间】:2015-07-24 00:23:57
【问题描述】:

使用 jQuery,我只想迭代某些元素。现在我有这个循环所有 DOM 元素及其每个属性的双循环:

  domElement.find('*').each(function () {  //loop over all child elements inside parent

                $.each(this.attributes, function (i, attrib) {
                    var name = attrib.name;
                    var value = attrib.value;

                });
            });

我的问题是 - 我可以以某种方式选择一组标签进行循环,而不是循环遍历所有元素 (*),例如仅跨度、输入、按钮、表单等?

更详细的方式是这样的:

      domElement.find('*').each(function () {  //loop over all child elements inside parent

               if(this.tagname is in ['span','input','button','form']){  //pseudocode

                    $.each(this.attributes, function (i, attrib) {
                        var name = attrib.name;
                        var value = attrib.value;


                    });
                 }
            });

【问题讨论】:

  • 您是否尝试将* 替换为span, input, button, form
  • 当然。 .find('span,input,button,form') 会起作用。
  • “jQuery 的 find 做了什么”api.jquery.com/find
  • 了解什么是 CSS 选择器。这对 Web 开发至关重要。
  • 好吧,为了避免使用 RTFM 棒太难受,阅读更多关于 jQuery 的介绍性材料可能会有所帮助。 jQuery 的绝大多数 API 允许您传入选择器字符串,正如 @minitech 所指出的,它们对于一般的 Web 开发非常重要。这可能是一篇关于选择器的有用文章:learn.jquery.com/using-jquery-core/selecting-elements

标签: javascript jquery html


【解决方案1】:

使用多个选择器:JQuery Documentation

我认为在您的示例中,代码应该是这样的:

var selectList = $('span, input, button, form');

【讨论】:

    【解决方案2】:

    试试这个:

    $('span,input,button,form').each(function (i, attrib) {
        var name = attrib.name;
        var value = attrib.value;
    });
    

    虽然 Mouhamed Halloul 的建议更好,但给他们一个公共类然后循环该类:

    $('.common-class-name').each(function (i, attrib) {
        var name = attrib.name;
        var value = attrib.value;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      相关资源
      最近更新 更多