【问题标题】:Finding elements with dynamic Id查找具有动态 ID 的元素
【发布时间】:2012-04-13 19:19:36
【问题描述】:

我想在 jquery 中创建一个通用函数来选择所有功能。我的网页中有一个选项卡式视图。

我的组件 ID 是:tabId:someDynamicId:rowId:componentId 其中,someDynamicId 是动态生成的。

所以在 jquery 中,我想找到 id 以 - tabId:someDynamicId & 以 componentId 开头的元素。并且,tabId、someDynamicId 和 componentId 将作为参数传递给需要查找此元素的通用函数。

【问题讨论】:

    标签: jquery jquery-selectors primefaces


    【解决方案1】:

    很简单:

    $('[id^=tabId][id$=componentId]').each(function(){
        var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId​
        var list = id.split(':');​​
    
        console.log(list[0]); // tabId
        console.log(list[1]); // someDynamicId
        console.log(list[2]); // rowId
        console.log(list[3]); // componentId​
    })
    

    Wildcards in jQuery selectors

    但我建议使用正确的工具来完成这项工作。 ID 对于查找特定元素很有用,但在您的情况下,最好使用一两个类和数据属性。例如:

    <div class="tabs" data-component-id="x" data-tab-id="y">
    

    然后找到所有 $('.tabs') 元素并使用 $(this).data('component-id') 和 $(this).data('tab-id')

    $('.tabs').each(function(){
        var component_id = $(this).data('component-id');
        var tab_id = $(this).data('tab-id');
    });
    

    更新:

    有使用 this 作为函数的例子:

    function(tabId,componentId) {
        $('[id^='+tabId+'][id$='+componentId+']').each(function(){
            var id = $(this).attr('id'); // tabId:someDynamicId:rowId:componentId​
            var list = id.split(':');​​
    
            console.log(list[0]); // tabId
            console.log(list[1]); // someDynamicId
            console.log(list[2]); // rowId
            console.log(list[3]); // componentId​
        })  
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式和filter() 做到这一点。像这样的东西应该工作。此特定示例查找以“one”开头、后跟数字并以“two”结尾的 id。检查示例http://jsfiddle.net/5eXm4/

      $.fn.regexFindId = function(re){
          return this.filter(function(){
              var id = this.id;
              return id.match(re);
          });
      };
      

      编辑:您可以在正则表达式中使用变量,只需像这样声明它们:

      var re = new RegExp(myVar);
      

      【讨论】:

      • 好兄弟,但我想使用变量。我不能像在正则表达式中那样对我的函数进行硬编码,因为在我的情况下,我不知道 id 会以 one or two or three 开头。那怎么办???请回复。
      • 您必须从您的 id 中提取一个模式并与之匹配。典型的组件 ID 是什么样的?另见编辑
      【解决方案3】:
       function( tableid, dynamicid, componentid)
         {
           a  = tableid+dynamicid ;    
           $( " [id^="+a+"][id$="+componentid+"] "). each(function()
           {
                        // do ur stuff
           }
          );
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-09
        • 2014-09-27
        • 2021-05-28
        相关资源
        最近更新 更多