2014-09-22 3 views
0

함수에서 특정 이벤트를 얻는 방법을 이해하려고합니다. 나는 console.log(this)을 수행 할 때함수에서 특정 이벤트를 얻는 방법

$('#removeItem').click(function() { 
    // $('option:selected', this).remove(); 
    console.log(this); 
    $(this).find('option:selected').remove(); 
}); 

, 실제로 "removeItem"에 대한 요소를 인쇄 :

<select id="mySelect" multiple="multiple" width="50"> 
</select> 
Remove Item<input type="button" id="removeItem" value="click" disabled="disabled"/> 

내 jQuery를 기능은 다음과 같습니다

<input type="button" id="removeItem" value="click"> 

다음은 내 HTML 코드

그러나 함수 내에서 "mySelect"(내 selectBox)에 대한 참조가 필요하므로 다음과 같이 실행할 수 있습니다.

$('option:selected', this).remove(); 

답변

0

데이터 요소를 사용하거나 직접 #id 요소를 사용할 수 있습니다.

HTML :

<input type="button" id="removeItem" value="click" data-target='#mySelect' /> 

JS :

$('#removeItem').click(function(){ 
    $('option:selected', $($(this).data('target'))).remove(); 
}); 

Demo JSFiddle

1

$("#removeItem").click(function(){ 
 
\t $("#mySelect option:selected").remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
 

 

 

 
<select id="mySelect" multiple="multiple" width="50"> 
 
    <option>1</option> 
 
    <option>2</option> 
 
    <option>3</option> 
 
    <option>4</option> 
 
</select> 
 
Remove Item<input type="button" id="removeItem" value="click"/>

+0

감사 그레고리에 더 잘 이해 this를 들어

$("#mySelect option:selected") 

를 사용하는 것이 좋습니다. 이 작품은 "# mySelect"요소에 "this"키워드를 사용하여 액세스 할 수있는 방법이 있는지 알고 싶습니다. 현재 "this"는 버튼 항목을 나타냅니다. 기본적으로 "#mySelect"요소에 대한 컨텍스트를 전달하는 방법이 있는지 이해하고 싶습니다. 당신이 날 잡기를 바래요. – user3599032

0

당신은 요소를 사용할 수있는 ID 직접

console.log(mySelect); 
$('option:selected', mySelect).remove(); 

자바 스크립트

에서하지만 이벤트 범위 Function.prototype.apply()

관련 문제