对于每个 ID,删除三个字母并添加两个字母

for each ID remove three letters and add two letters

我正在从页面上的所有标签中获取 ID。我知道要从中删除三个字母并用两个字母替换它们。

我得到以下信息:

(function ($) {
  $(document).ready(function() {
    $('label').each(function(index) {
      var id = $(this).attr('id');
      var idm = id.replace('lbl','cg')
      $(this).parents('.control-group').addClass(idm);
    });
  });
})(jQuery);

但是我收到错误 Cannot read property 'replace' of undefined

在我的第一次尝试中,我是这样写的,但得到了同样的错误:

(function ($) {
  $(document).ready(function() {
    $('label').each(function(index) {
      var id = $(this).attr('id').replace('lbl','cg');
      $(this).parents('.control-group').addClass(id);
    });
  });
})(jQuery);

But I get the error Cannot read property 'replace' of undefined

这可能是因为您的 <label> 元素之一没有定义 id 属性。

您可以考虑只定位您已知具有 id 属性的 <label> 元素,如下所示使用 the has attribute selector :

// Only target a label with a defined id attribute
$('label[id]').each(function(index) {
   var id = $(this).attr('id').replace('lbl','cg');
   $(this).parents('.control-group').addClass(id);
});