jQuery HTML 태그에 값이나 html 설정해야 하는 경우, Html 태그 별로 각각 사용하는 함수가 다르다.

 

그러므로 개발을 진행하다고, 함수를 찾아보거나, html 값이 적재되지 않는 이유를 찾지 않아도 된다.

( 예를 들어 span 경우, val() 함수를 사용하고, 값이 들어갔지라는 의문을 가질 필요가 없다. )

 

따라서, 매번 Html 태그를 확인해서 함수를 사용하기 보다는 미리 html 값을 설정 있는

 

getter, setter 함수를 생성하고 사용하는 편이 나중을 생각해서도 편하다.



소스코드 예시

jQuery.fn.extend({

    setValue: function (value) {

      if ( $(this).is("input") || $(this).is('textarea') || $(this).is('select') ){

              $(this).val(value);

      }else{

              $(this).text(value);

      }

    },

    getValue : function(){

      if ( $(this).is("input") || $(this).is('textarea') || $(this).is('select') ){

              return $(this).val();

      }else{

              return $(this).text();

      }

    }

});


//사용법

$('#id').setValue('test');

console.log($('#id').getValue());


'프로그래밍 > jQuery' 카테고리의 다른 글

반복적 비동기 호출  (0) 2019.02.27
[jQuery] scrollTop 을 이용한 textarea focus  (0) 2012.08.22
[jQuery] each()  (0) 2012.05.10
[jQuery] attr()  (0) 2012.04.25
[jQuery] jQuery.each() vs .each()  (1) 2012.04.24