2013-04-11 75 views
1

的獲取來源我有一個HTML表單多個元素,類似以下內容:JQuery的.change - 事件

<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的,和ID form_area_id的其中id爲唯一的整數。

我試圖使用jQuery寫,當用戶更改選擇框的事件處理程序。

所有我已經成功地得到到目前爲止是這樣的:

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

有沒有什麼辦法讓事件處理程序確切地知道哪些選擇是事件的來源是什麼?

回答

2

this內,甚至是指觸發事件的控制:

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

那是你要什麼?或者您可以在回調中接受e並查看e.target。上event.target

如果你想獲得選擇(只數)的ID

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

文檔,你可以使用:

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

對源對象可以使用this,對源對象id可以使用this.id

Live Demo

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

可以使用$(this)得到觸發控制事件

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

this是源碼。事實上,綁定到事件的函數是在發生事件的項目的上下文中調用的。所以它只是:

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

您應該使用['.prop()''以上.attr()'](http://stackoverflow.com/問題/ 5874652 /道具-VS-attr)使用,特別是如果你要訪問本地[屬性](https://developer.mozilla.org/en-US/docs/DOM/element#Properties)。更好的辦法是完全排除jQuery並引用['this.id'](https://developer.mozilla.org/en-US/docs/DOM/element.id)。 – 2013-04-11 15:39:13

1

我想你需要this

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