【问题标题】:Foreach label get id - modify this id - add to parent classForeach 标签获取 id - 修改此 id - 添加到父类
【发布时间】:2017-02-06 20:42:57
【问题描述】:

我正在尝试为 Joomla CMS 后端的每个模块制作一个通用代码。代码需要从标签中获取ID,并将这个ID作为一个类添加到最近的父类control-group

Joomla 模块的基本构建:

<div class="control-group">
  <div class="control-label">
    <label id="jform_params_some_text_here-lbl" for="jform_params_some_text_here" class="hasPopover"></label>
  </div>
  <div class="controls"></div>
</div>     

普遍做到这一点的最佳方法是什么

我知道我可以单独设置:

 (function ($) {
   $(document).ready(function() {
     $("#jform_params_some_text_here-lbl").parents(".control-group").addClass("jform_params_some_text_here-cg");
   });
 })(jQuery);

但我需要让它通用。

我想达到什么目的

  1. Foreach 标签获取 id。
  2. 删除字母lbl并替换为字母cg
  3. 找到最近的父类control-group
  4. 将刚刚重命名的类添加到这个父类

感谢大家的帮助!

【问题讨论】:

    标签: jquery foreach


    【解决方案1】:

    您可以利用 jQuery 的可用 has attribute selector 来仅定位具有已定义 id 属性的标签元素,以避免任何未定义的错误。

    然后您应该能够看到下面注释的首选步骤:

    // Step 1: Iterate through each label that has an `id` attribute
    $('label[id]').each(function(){
         // Step 2: Get your replacement id
         var id = $(this).attr('id').replace('lbl','cg');
         // Step 3: Find your nearest parent with "control-group" class
         var parent = $(this).parents('.control-group');
         // Step 4: Now set the class for your parent element
         parent.addClass(id);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多