2017-02-06 1 views
0

페이지의 모든 레이블에서 ID를 가져옵니다. 나는 그것에서 3 개의 편지를 제거하고 2 개의 편지로 그 (것)들을 교환하고 싶다. 은 세 글자를 제거하고 두 글자를 추가합니다.

나는 다음과 같은 가지고 :

(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); 
+0

는 라벨의 _all_이 ID를 가지고 수행

당신은 고려해 볼 수 있습니다

the has attribute selector를 사용하여 아래와 같이 이미 id 속성을 알고 <label> 요소를 대상으로? – Turnip

+0

ID가있는 모든 레이블을 검사 한 다음 실행하면 Rion의 대답과 함께 선택하기 때문에 범용 적이기 때문에 몰라요. – purple11111

답변

2

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

<label> 요소 중 하나에가 없기 때문일 수 있습니다.속성이 정의되었습니다.

// 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); 
}); 
+0

정말 고마워요. 마치 매력처럼 작동합니다. 10 분 안에 받아 들일 수있어. – purple11111

+0

약 20 분 전에 또 다른 질문을했고이 질문과 관련이 있습니다. 실제로 여기에서 제공하는 코드는 해당 질문에 필요한 정확한 코드입니다. 나는 다른 질문을 삭제해야합니까 (다른 질문 인 반면) 또는이 답변을 게시 할 수 있습니까? 아니면 게시해야합니까? http://stackoverflow.com/questions/42076925/foreach-label-get-id-modify-this-id-add-to-parent-class 그동안이 질문에 대한 링크를 게시했습니다. – purple11111

관련 문제