2014-09-22 20 views
0

我想了解如何在函數中獲取特定事件。
下面是我的HTML代碼:如何獲得函數中的特定事件

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

我jQuery的功能是這樣的:

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

以上,當我做了console.log(this),它實際上打印元素爲 「removeItem」:

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

但是,在函數中,我想引用「mySelect」(我的選擇框),以便我可以執行如下操作:

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

回答

0

您可以使用數據元素或使用直接#id元素。

HTML:

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

JS:

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」元素。目前「this」是指按鈕項目。基本上,我想了解是否有辦法通過「#mySelect」元素的上下文。希望你能找到我。 – user3599032 2014-09-22 16:02:19

0

您可以使用元素ID直接在JavaScript

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

但最好是使用

$("#mySelect option:selected") 

爲了更好地理解this事件範圍Function.prototype.apply()

相關問題