Kudos
Collect
Twiiter
Facebook
Share
Develop somethings, meditation, reading and thinking...

jQuery 로 template 태그 사용하기

마지막 업데이트 4년 전
3 0 0 2

화면에 표시되지 않는 template 태그를 유용하게 사용할 수 있는 방법으로 form 의 입력내용을 동적으로 표현하는 방법을 들 수 있습니다.

다음과 같이 아무 내용을 포함하지 않은 form+ add 버튼을 누르면 이름을 입력하는 input 이 동적으로 추가되도록 해 보겠습니다. + add 버튼을 계속해서 누르면 input 도 계속해서 추가됩니다.

<form action="some_where" name="a-form" class="form-wrapper">
    <!-- .input-wrapper will be here -->
</form>

<button type="button" class="input-add">+ Add</button>

추가될 input 의 템플릿 div.input-wrapper.

<template id="a-template">
    <div class="input-wrapper">
        <h3>
            Name
        </h3>
        <input type="text" name="name[]" class="name" placeholder="Richard Freeman" value="">
        <p>
            Please input your name.
        </p>
    </div>
</template>

버튼을 누르면 템플릿을 가져와서 input 값에 지정한 이름을 입력한 후 form 에 추가하는 자바스크립트 코드.

//
// jQuery required.
//
function addInput(name_val) {

    var $clonedTemplate  = $("#a-template").clone();
    var $templateContent = $($clonedTemplate.html());

    $templateContent.find('input.name').attr('value', name_val);

    $clonedTemplate.html($templateContent.prop('outerHTML'));

    $('.a-form').append($clonedTemplate.html());
}

$('.input-add').on('click', function(){
    addInput('Dummy Name');
});

addInput('Default Name');

여기서 중요한 부분은 다음과 같이 templateclone 하여, 템플릿 내용만 jQuery 오브젝트로 만든다. 이렇게 만들어진 오브젝트만이 jQuery 의 find 함수를 이용하여 내부의 DOM 를 마음대로 요리할 수 있게 된다. 요리한 jQuery 오브젝트를 다시 처음의 clone 한 템플릿으로 업데이트 하면

var $clonedTemplate  = $("#a-template").clone();
var $templateContent = $($clonedTemplate.html()); // 이렇게 해야만 ...

$templateContent.find('input.name').attr('value', name_val); // .find() 가 사용 가능해진다.

$clonedTemplate.html($templateContent.prop('outerHTML'));

console.log($clonedTemplate.html()); // 요리된 템플릿

jQuery 로 template 태그를 사용하려는 분에게 도움이 되기를 바랍니다.

Hi, my name is Richard. I’m a developer wants to make the world better with logic power. Mainly I use Linux, Nginx, MySQL, PHP and JavaScript . I want to share my knowledge with someone that it was also based from some great persons via LYNMP. 👨‍💻

Essedrop - 이미지 주소를 만드는 가장 빠른 방법
 

독자 의견

  • 덕분에 template 태그를 알아갑니다. 좋은 정보 감사합니다^^

    • $clonedTemplate.html($templateContent.prop('outerHTML'));
      

      이 부분이 포인트랍니다.
      도움이 되었다니 정말 다행이네요.

저자 @richard 에게 의견 남기기:

Please sign in to comment.
Markdown is also available in comment.