2013-03-18 20 views
1

屬性添加到`change`事件我有一個<select>框:如何在jQuery的

<select id="myselect"> 
    <option value="1">one</option> 
    <option value="2">two</option> 
    <option value="3">three</option> 
</select> 

我需要修改它的change事件,所以它有一個val_after_change財產,不管事件如何被觸發。

// THIS FUNCTION CANNOT BE MODIFIED 
$('#myselect').change(function(e){ 
    // this should alert select value after change 
    alert(e.val); 
}); 

我知道,在這裏我可以alert $(this).val(),但我的真實的例子更復雜,需要e.val。我知道這在select2有效,但我無法理解他們的源代碼。

如何修改事件?我需要做一個包裝或什麼?任何幫助將被appriciated。

編輯:

我做一個圖書館,使selects使用e.val財產的包裝,所以我不能修改change事件本身。當事件被觸發時,我需要屬性已經存在。像這樣的事情,但使之成爲默認水煤漿:

e = jQuery.Event('change', {val: 2}); 
$('#myselect').trigger(e); 

JsFiddle

+0

是什麼讓這麼多$(this).val()不起作用更復雜嗎? – 2013-03-18 13:19:47

+0

@Jay Blanchard,我正在圍繞「select2」做一個包裝。這是'change'事件期望擁有'val'屬性 – 2013-03-18 13:23:06

回答

0

我不SUR我知道了,這裏是一個鏡頭吧:

(function ($){ 
    // keep a copy of the original "select2" function 
    var lib_select2 = $.fn.select2; 

    // wrap it into a call which 
    // first adds a listener to add the value as a property of the event, 
    // then adds whatever extra stuff the library adds 
    $.fn.select2 = function(){ 
     this.change(function(e){ 
      e.val = this.value; 
     }); 

     lib_select2.apply(this, arguments); 
    } 
})(jQuery)