2014-09-22 41 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()