2011-09-23 3 views
0

함수에 onlick 이벤트를 첨부했습니다. 내부 HTML을 변경할 수 있도록 함수 내부에서 클릭 한 요소를 참조하려고하지만 왜 작동하지 않습니까? 클릭 된 요소를 참조 할 수있는 다른 방법이 있습니까?

HTML

 <div class="save_button" onclick="toggle_save_star(<?php echo $listing->listing_id ?>,'<?php echo base_url()?>')"> 
      <?php if($listing->saved_element_id):?> 
      <img src="<?php echo site_url('images/core/icons/basic2/star1_16.png')?>" /> 
      <?php else:?> 
      <img src="<?php echo site_url('images/core/icons/basic2/star1_16_gray.png')?>" /> 
      <?php endif; ?> 
     </div> 

자바 스크립트 기능

function toggle_save_star(element_id, site_url) { 
    var url = site_url+"AJAX/ajax_default/modify_saved"; 
    var button = $(this); 
    $.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) { 
     if(data == 'saved') { 
      $(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />'); 
     } 
     else{ 
      $(button).html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />'); 
     } 
    }); 
} 

답변

2

대신 $("#"+element_id)을보십시오. $(this)은 개체의 메서드로이 함수를 실행하지 않기 때문에 작동하지 않습니다. 다른 답변에 개선

,이 시도 :

var button = target; 
: 세 번째 새로운 인수가
$(".save_button").click(function(){ 
toggle_save_star(element_id, site_url, $(this)); 
}); 

및 함수에

다음과 같이 사용될 수있다 (라고는 " target"의 말을하자)

다음 버튼을 사용하십시오 button.html(...);

4

이 경우 "this"는 div를 참조하지 않아야한다고 생각합니다. 당신이 시도해야합니다

$('.save_button').click(function(){ 
    $(this)... 
}); 
+0

이 정보는 문제를 해결하는 데 도움이되는 제안입니다. – Christian

+0

어쩌면 내가 잘못 생각한 것일 수도 있지만, 관련 HTML 페이지 전체를이 코드로 옮기지 않을까요? 그렇지 않다면이 두 가지 논점을이 방법으로 작성하면 어떻게 될까요? – emkay

+0

나는 더 나은 설명을 위해 나의 대답을 업데이트했다. – Christian

0

여기서 가장 큰 문제는 당신이로 마크 업에 온 클릭 문자열을 할당 할 때이다 : 다음

<div class="save_button" onclick="toggle_save_star..." 

, 따옴표의 코드가 평가에 의해 평가됩니다() this 포인터는 클릭을 생성 한 개체가 아니라 window 개체를 가리 키도록 설정됩니다. 당신이 적절하게 this 세트를 원하는 경우에, 당신은 마크 업에서 온 클릭 핸들러를 할당 할 수 없습니다, 당신은 같이 JS와 함께 할 필요가있을 것이다 :

$(".save_button").click(); 

또는 코드에서 다른 방법.

또한 toggle_save_star 함수에 코딩 오류가 있습니다.

귀하의 button 변수는 이미 jQuery 객체이므로 $(button)을 사용하여 변수를 다른 것으로 만들 필요가 없습니다. 당신이 그 기능을 사용하려고한다면, 당신이 그것을 변경해야 할 것 :

function toggle_save_star(element_id, site_url) { 
    var url = site_url+"AJAX/ajax_default/modify_saved"; 
    var button = $(this); 
    $.post(url,{action: 'toggle', element_id: element_id, type: 'listing' }, function(data) { 
     if(data == 'saved') { 
      button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16.png" />'); 
     } 
     else{ 
      button.html('<img src="'+site_url+'images/core/icons/basic2/star1_16_gray.png" />'); 
     } 
    }); 
} 
0

당신은 당신의 사업부에서 온 클릭을 제거하고 다음과 같이 뭔가 함께가는 더 나을 것 :

http://jsfiddle.net/cpeele00/epD3v/

클릭 할 수있는 항목 (이 경우 'save_button')에 액세스 할 수 있습니다.

그런 다음 페이지 맨 아래에 (닫는 body 태그에 도달하기 전에 스크립트를 삽입하십시오.)

<script> 

    $(document).ready(function(){ 

    //CALL THE FUNCTION HERE   


    //DEFINE THE FUNCTION HERE (see the jsFiddle link above) 

    }); 

</script> 
</body> 
관련 문제