2017-03-08 1 views
1

버튼이 들어있는 옥 템플릿에서 동적으로 생성 된 객체가 있습니다. 그 안에있는 버튼을 클릭하면 객체를 가져올 수 있어야합니다. 저는 여기에 현재동적 버튼 jQuery가 포함 된 객체 가져 오기

mixin ad(name,media,payout) 

.box.box-primary 
    .box-header.with-border 
    h3.box-title=name 

    .box-body 
    img(src=media, style='width:130px;height:100px;') 
    p.text-muted.text-center="$"+payout 
    p.text-muted.text-center preview 
    .box-footer.text-right 
    button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf()') Share 

나는 그냥 "정의되지 않은"인쇄하지만 어떻게 내가 이름을 인쇄 때문에 내 jQuery를이 잘못 알고있는 jQuery를

var getSelf = function() { 
    var clickedBtnID = $(this).parent(); 
    alert('you clicked on button #' + clickedBtnID.name); 
} 

이 무엇인가?

감사합니다.

답변

1

지금까지 thisbutton 요소를 나타내지 않으므로 window 개체를 나타냅니다.

는 나중에 사용할 수있는 참조를 허용하도록 함수를 수정하는 기능

button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf(this)') 

this 참조를 전달할 수 있습니다.

var getSelf = function(elem) { 
    var clickedBtnID = $(elem).parent(); 
    alert('you clicked on button #' + clickedBtnID.name); 
} 

그러나 나는 눈에 거슬리지 이벤트 핸들러 대신 추악한 인라인 클릭 핸들러를 (그것을 제거)를 사용하는 당신에게 추천 할 것입니다.

$(function(){ 
    $("#share").on('click', function(){ 
     var clickedBtnID = $(this).parent(); 
     alert('you clicked on button #' + clickedBtnID.name); 
    }); 
}) 
+0

패스 '온 클릭 함수 파라미터로서 elem'. –

+0

@Agalo의 솔루션을 사용하여 "this"참조를 캡처/전달하는 대신 이벤트 대상을 캡처하는 것이 더 좋습니다. –

0

event.target 속성을 사용하여 이벤트를 트리거 한 요소를 참조 할 수 있습니다. 이벤트 정보는 첫 번째 매개 변수로 이벤트 핸들러에 전달됩니다.

완전한 작업 코드.

$('div').click(function(event){ 
 
console.log(event.target.id) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="div1">div1</div> 
 
<div id="div2">div2</div> 
 
<div id="div3">div3</div> 
 
<div id="div4">div4</div> 
 
<div id="div5">div5</div>

+1

'event.target.closest ('. box.box-primary')'와 같은 것이 더 안전하고 미래 보장 될 수 있지만,'parent()'참조를 얻는 것을 잊은 점을 제외하고는 정확한 해결책입니다. –

관련 문제