본문 바로가기

JavaScript

[JavaScript] 동적 태그에서 스크립트 호출하기.

반응형


동적 생성 태그를 사용하다 onClcik등의 이벤트를 주어야 하는 경우가 발생하였다.

이 경우 문자열로 구분을 제대로 주지 않으면.

<a> 태그가 깨지는 상황이 발생하여 스크립트를 실행하지 못하는경우가 종종 생기게 되는데.


 태그가 깨지는 경우

※ 이런식으로 태그가 깨져서 출력되었다. <a zgmf-x10a);'="" y',="" onclick="alertOpen(" href="javascript:;">0</a>


\기호를 잘 입력해 줌으로서 해결할 수 있다.


아래 코드를 예러 들자면.


 dynamic_tag.php

<html>
<head>
<title>건담 파일럿 리스트</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">

var array = new Array();
array[0] = { "title" : "프리덤", "pliot" : "키라 야마토", "code" : "ZGMF-X10A" }
array[1] = { "title" : "저스티스", "pliot" : "아스란 자라", "code" : "ZGMF-X09A" }
array[2] = { "title" : "데스티니", "pliot" : "신 아스카", "code" : "ZGMF-X42S" }
array[3] = { "title" : "엑시아", "pliot" : "세츠나 F 세이에이", "code" : "GN-001" }
array[4] = { "title" : "아리오스", "pliot" : "알렐루야 합티즘", "code" : "GN-007" }
array[5] = { "title" : "듀나메스", "pliot" : "록온 스트라토스", "code" : "GN-002" }
array[6] = { "title" : "스트라이크 느와르", "pliot" : "스웬 칼 바얀", "code" : "GAT-X105E" }
array[7] = { "title" : "세이버", "pliot" : "아스란 자라", "code" : "ZGMF-X23S" }
array[8] = { "title" : "윙 제로 EW", "pliot" : "히이로 유이", "code" : "XXXG-00W0" }
array[9] = { "title" : "데스사이즈 EW", "pliot" : "듀오 맥스웰", "code" : "XXXG-01D2 " }


function dynamicData() {
   
    var tableList = "";

    for(var i = 0; i < array.length; i++) {
       
        // tableList += "<tr><td width=\"50px\">" + i + "</td><td width=\"500px\"><a href=\"javascript:;\" onClick=\"alertOpen('Y', '" + array[i]['code'] + "');\">" + array[i]['title'] + "</a></td><td width=\"200px\">" + array[i]['pliot'] + "</td></tr>";

        tableList += "<tr>";
        tableList += "<td width=\"50px\">" + i + "</td>";
        tableList += "<td width=\"500px\"><a href=\"javascript:;\" onClick=\"alertOpen('Y', '" + array[i]['code'] + "');\">";
        tableList += array[i]['title'] + "</a></td>";
        tableList += "<td width=\"200px\">" + array[i]['pliot'] + "</td>";
        tableList += "</tr>";
    }

    jQuery("#dynamicTable").html(tableList);
}

function alertOpen(on, code) {
   
    if(on == "Y") {

        alert(code);
    }
}
</script>
</head>
<body>
<table border="1">
    <tr>
        <th width="50px">번호</th>
        <th width="500px">제목</th>
        <th width="200px">파일럿</th>
    </tr>
</table>
<table border="1" id="dynamicTable"></table>
<br/>
<input type="button" onClick="dynamicData();" value="데이터 불러오기"/>
</body>
</html>

 출력결과

 출력결과 List On



위 코드와 같이 ""(따옴표)가 사용되는 곧 앞에 \기호를 입력함으로선 브라우저상에선 따옴표를 인식시켜서 해결해야 한다.


 동적태그에서 스크립트 호출

tableList += "<td width=\"500px\"><a href=\"javascript:;\" onClick=\"alertOpen('Y', '" + array[i]['code'] + "');\">" + i + "</a></td>";





반응형