2013-05-04 4 views
-1

두 번 이상 실행하려면이 코드가 필요합니다. 단추를 클릭하여 이미지를 추가 한 경우에만 실행되고 단추를 클릭하면 이미지가 제거됩니다. 세 번째 클릭은 귀하의 게시물을 수정하기 때문에 그것은 당신에게 다른 대답을 줄 수있는 더 좋은 방법은, 글쎄 이미지를 다시이 함수를 두 번 이상 실행하는 방법 JavaScript/jQuery

<button class="" onclick="showImages(this,'100000,jpg','1111111.jpg','5');"></button> 
<div id="5" class=""> 
... //when I run the function it appends the <img> tag here 
</div> 

function showImages(button, image1, image2, id) { //user clicks a button "show" 
    if (image2 == "") { //if there is only one image 
     $('#show' + id + '').append('<img class=\"one\" src=\"images/' + image1 + '\" />'); //creates a div with 1 image 
     button.onclick = function() { //clicks it second time 
      $('#show' + id + '').empty(); //removes the div with image 
     }; 
    } else { //if there are 2 images 
     $('#show' + id + '').append('<img class=\"two\" src=\"images/' + image1 + '\" /><img src=\"images/' + image2 + '\" />'); //div with 2 images 
     button.onclick = function() { //... 
      $('#show' + id + '').empty(); //... 
     }; 
    } 
} 
+3

는 "어떻게 그렇게 말을, 24을이 기능을 실행할 수 있도록?" 나는 질문을 이해할 수 없다 –

+0

역시 나를 볶아 버렸다. 그는 심지어이 코드를 사용하는 코드도 넣지 않았습니다. 자세한 정보를 제공해주십시오. – WooCaSh

+0

거기서 바뀌 었습니다 ... 지금은 분명합니까? –

답변

0

를 추가하지 않습니다. 이 onclick="showImages(this,'100000,jpg','1111111.jpg','5');"에 의해 버튼 클릭시 하나의 핸들러가 연결되었습니다. 나중에이 button.onclick = function() { $('#show' + id + '').empty(); };에서 하나 더 핸들러를 제공했습니다. 이제 두 개의 핸들러가 있습니다. 하나는 핸들러이고 다른 하나는 이미지를 보여줍니다. 이것이 코드가 한 번만 작동하는 이유입니다 (두 번째 처리기가 바인드되지 않을 때까지).

수정하십시오. HTML :

<button id="my_button" image_1="10000.jpg" image_2="1111111.jpg" target_id="5"></button> <!-- move away javascript from HTML; put necessary data in button attributes --> 
<div id="5"> 
... 
</div> 

그리고 자바 스크립트 :

var toggleImages = function(event){ 

    /* retrieve clicked button itself and all needed attributes */ 
    var button = $(event.target), 
     image_1 = "images/" + button.attr('image_1'), 
     image_2 = "images/" + button.attr('image_2'), 
     target = $('#' + button.attr('target_id')); 

    /* if no images shown – show it */ 
    if(0 == target.find('img').length){ 
    target.append('<img src="' + image_1 + '" />'); 
    if('undefined' != typeof image_2){ 
     target.append('<img src="' + image_2 + '" />'); 
    } 
    /* if images was shown – remove it */ 
    } else { 
    target.empty(); 
    } 
} 
$('#my_button').on('click', toggleImages); /* bind click handler only one time */ 
관련 문제