$('#target').change(function(){ //執行想要的程式 });
若是有n個,我都會很偷懶的複製n次,在這行業混了十來年,這做法一直沒變,很少需要改(難怪有人講老狗玩不出新把戲 @@)
不過今天正好就遇到需要的狀況,兩個不同的target,要傳入的預設值不同,動作幾乎一樣,這樣定義兩次實在很蠢,所以查了下jQuery.change,截部分如下:
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
version added: 1.0.change( handler )
- handlerA function to execute each time the event is triggered.
version added: 1.4.3.change( [eventData ], handler )
- eventDataType: AnythingAn object containing data that will be passed to the event handler.
- handlerA function to execute each time the event is triggered.
version added: 1.0.change()
- This signature does not accept any arguments.
所以如下使用
$('#targetA').change({target: 'A'},demo); $('#targetB').change({target: 'B'},demo); function demo(event){ alert(event.data.target); }
這樣由targetA啟動change就會alert出A,由targetB啟動change就會alert出B了
參考網址:
jQuery.change
How to use a function that takes arguments with jQuery's change() method?
沒有留言:
張貼留言