JQuery .change - 获取事件源

时间:2013-04-11 15:30:29

标签: javascript jquery

我在HTML表单上有许多元素,类似于以下内容:

<div class="area">
    First Area
    <select class="area_select" name="area_25" id="form_area_25">
        <option value="0" selected="selected">No</option>
        <option value="1" >Don't Mind</option>
        <option value="2" >Yes</option>
    </select>
</div>

<div class="area">
    Second Area
    <select class="area_select" name="area_13" id="form_area_13">
        <option value="0" selected="selected">No</option>
        <option value="1" >Don't Mind</option>
        <option value="2" >Yes</option>
    </select>
</div>
    .... and many more

它们都有一个area_select类,以及form_area_id的id,其中id是一个唯一的整数。

我正在尝试使用jQuery为用户更改选择框时编写事件处理程序。

我到目前为止所做的一切都是:

$(".area_select").change(function() {
  alert('select changed, but no idea which one');
});

有没有办法让事件处理程序确切地知道哪个选择是事件的来源?

5 个答案:

答案 0 :(得分:2)

偶数内的

this指的是触发事件的控件:

$('.area_select').change(function(){
  // this = the control
});

这就是你想要的吗?或者您可以在回调中接受e并查看e.target

$('.area_select').change(function(e){
  // e.target = the control (unless bubbling occurred)
});

event.target

上的文档

如果您想获得可以使用的选择ID(只是数字):

$(".area_select").change(function() {
    var selectid = this.id.match(/(\d+)$/)[1];
});

答案 1 :(得分:1)

您可以将this用于源对象,将this.id用于源对象id

<强> Live Demo

$(".area_select").change(function(event) {
  alert(this.id);
});

答案 2 :(得分:1)

您可以使用$(this)来获取触发事件的控件

$(".area_select").change(function() {
   alert($(this).attr("id") + " changed");
});

答案 3 :(得分:1)

this是来源。实际上,绑定到事件的函数是在事件发生的项的上下文中调用的。所以它很简单:

$(".area_select").change(function() {
  alert('select ' + $(this).attr("id") + " changed");
});

答案 4 :(得分:1)

我认为你需要this

$(".area_select").change(function() {
      alert('select changed: '+$(this).val()+' , but no idea which one: '
      +$(this).attr('id').replace('form_area_',''));
});
相关问题