2013-09-01 9 views
-1

jQuery를 사용하여 버튼 클릭으로 페이지에 동적으로 추가되는 Div가 있습니다.Div의 id를 함수의 인수로 전달하는 방법

RemoveArtist() 기능을 사용하여 cross-button.png 클릭으로 Div를 제거하고 싶습니다.

$("<div class=\"input-append\" id=\"artist" 
    + artists.length - 1 + "\" ><label style=\"background-color:#e0ffff\">" 
    + artistVal + "</label><img onclick=\"RemoveArtist()\" id=\"removeartist\"" 
    + " src=\"/Content/bootstrap/img/cross-button.png\" /></div>") 
    .appendTo(addDiv); 

제거 아티스트 fucntion은 다음과 같아야합니다

var RemoveArtist = function (div,artistlength) { 

    $('div').remove(); 
    artists.splice(artistlength, 1); 
}; 

가 어떻게 또한 실제 RemoveArtist 함수 사업부와 사업부의 artists.length - 1 값이있는 artistlength를 전달할 수 있습니다?

그래서 기본적으로 Div를 삭제하고 아티스트 배열에서 아티스트를 삭제하려고합니다.

+0

그냥 조언 : 당신이 jQuery를 사용하는 경우, 기존의 이벤트가 등록 사용하지 마십시오. 그것을 위해 jQuery를 사용하십시오. 따라서 'onclick'속성은 없습니다. – MaxArt

답변

1

제 생각에는 문자열 대신 실제 요소를 만든 경우 더 좋을 것입니다.
그것은 쓸 수있는 더 많은 물건,하지만 추적 유지하기 위해 훨씬 더 쉽게 everyhing한다 :

var input_append = $('<div />', {id: 'artist' + (artists.length - 1)}), 
    label  = $('<label />', {style: 'background-color:#e0ffff', 
            text : artistVal 
            } 
        ), 
    image  = $('<img />', {id: 'removeartist', 
           src: '/Content/bootstrap/img/cross-button.png', 
           on: { 
             click: function() { 
              input_append.remove(); 
              artists.splice(artists.length - 1, 1); 
             } 
            } 
           } 
        ); 

addDiv.append(input_append.append(label, img)); 
+0

+1하지만 조금 너무 많이 보입니다. 이미지에'on.click' 만 사용하고 나머지는 IMO 문자열에 넣을 수 있습니다. – MaxArt

+0

@MaxArt - 확실한 방법은 HTML 문자열에서 벗어나 jQuery 객체 또는'document.createElement'를 사용하여 실제 요소를 사용하는 것입니다. 제 생각에는 코드와 코더를 더 좋게 만들 것입니다. 일단 익숙해지면 읽는 것이 훨씬 쉬워집니다. – adeneo

+0

모든 것이 작동하지 않습니다. artists.splice (artists.length - 1, 1); – Milligran

관련 문제