我正在尝试制作一个通用代码,可以在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);
但我需要让它普遍存在。
我想要实现什么
- 对于每个标签获取 ID。
- 删除字母
lbl
并替换为字母cg
- 通过班级
control-group
查找最近的家长 - 将刚刚重命名的类添加到此父类
感谢大家的帮助!
您可以利用 jQuery 可用的 has 属性选择器来仅针对具有已定义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);
});