prosource

jQuery - 클래스 대신 ID 추가

probook 2023. 10. 10. 20:38
반응형

jQuery - 클래스 대신 ID 추가

현재 jQuery를 사용하고 있습니다.

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').addClass($(this).text());
        $('#container').addClass($(this).text());
        $('.stretch_footer').addClass($(this).text())
        $('#footer').addClass($(this).text());
    });
});

빵 부스러기에 들어 있는 텍스트를 페이지의 4가지 요소에 적용하여 페이지에 맞게 스타일을 지정할 수 있습니다.

수업 대신 신분증을 추가해보고 싶은데 어떻게 하면 될까요?

시도해 보기:

$('element').attr('id', 'value');

그래서 다음과 같습니다.

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').attr('id', $(this).text());
        $('#container').attr('id', $(this).text());
        $('.stretch_footer').attr('id', $(this).text())
        $('#footer').attr('id', $(this).text());
    });
});

따라서 세 요소의 ID를 변경/ 덮어쓰고 한 요소에 ID를 추가하는 것입니다.필요에 따라 수정할 수 있습니다...

요소가 이미 가지고 있는 ID를 덮어씁니다.

 $(".element").attr("id","SomeID");

이유addClass존재하는 이유는 요소에 여러 개의 클래스가 있을 수 있으므로 이미 설정된 클래스를 덮어쓸 필요가 없기 때문입니다.그러나 대부분의 속성에서 한 번에 허용되는 값은 하나뿐입니다.

$('selector').attr( 'id', 'yourId' );

교체가 아닌 'id에 추가'를 원하는 경우

먼저 현재 ID를 캡처한 다음 새 ID를 추가합니다.특히 입력 상태를 양식에 사용하는 트위터 부트스트랩에 유용합니다.

    new_id = '{{old_id}} inputSuccess';
    old_id = that.attr('id');
    that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));

그렇지 않은 경우 - 이전에 설정한 속성을 모두 잃게 됩니다.

hth,

커피스크립트로 하고 있습니다.

booking_module_time_clock_convert_id = () ->
  if $('.booking_module_time_clock').length
    idnumber = 1
    for a in $('.booking_module_time_clock')
      elementID = $(a).attr("id")
      $(a).attr( 'id', "#{elementID}_#{idnumber}" )
      idnumber++

언급URL : https://stackoverflow.com/questions/2176986/jquery-add-id-instead-of-class

반응형