2011-05-18 37 views
1

我有一個HTML腳本,用下面的代碼輸入框找到觸發事件

<input type="text" name="" id="PrDisplay" onkeyup="calcCosting()"/></td> 
    <input type="text" name="" id="PrFreight" onkeyup="calcCosting()"/></td> 

我有很多行這樣,當任何輸入框有一個條目,然後我的JQ功能被觸發

這是JS代碼

function calcCosting() { 

// calculate the sum of all the chargable items 
dis = $('#PrDisplay').val() /1 ; 
fre = $('#PrFreight').val() /1 ;  
pro = $('#PrProcess').val()/1 ; 
str = $('#PrStructual').val() /1 ; 
gro = $('#PrGroundworks').val()/1 ; 
sof = $('#PrSoftware').val() /1 ; 
har = $('#PrHardware').val() /1 ; 
add = $('#PrAdditional').val() /1 ; 

tot = dis + fre + pro + str + gro + sof + har + add; 
$('#PrTotal').val(tot) ; // display the total 
    } 

這工作得很好,並添加了所有的總數與ID PrTotal測試框中顯示它們。

我想在我的JQ腳本中執行的操作是找到觸發腳本調用的文本框,或者調用腳本時調用哪個框。我希望這是有道理的 !! ,我真的無法去處理這個元素有人可以給我一些指針嗎?

在此先感謝

回答

3

你可以簡單地在代碼中使用onkeyup="calcCosting(this)",並獲得calcCosting函數中的那個參數。

更新:

還可以綁定事件到<input>標籤與JS/jQuery的(而不是使用HTML屬性),方便地訪問this對象:

document.getElementById('PrDisplay').onkeyup=calcCosting; 
0

你可以試試這個代替,將其綁定並一次全部分配在jQuery的功能,像這樣:

$("input:text").bind("keyup", function() { 
    // $(this) == current input (type=text) element 

    // calculate the sum of all the chargable items 
    dis = $('#PrDisplay').val() /1 ; 
    fre = $('#PrFreight').val() /1 ;  
    pro = $('#PrProcess').val()/1 ; 
    str = $('#PrStructual').val() /1 ; 
    gro = $('#PrGroundworks').val()/1 ; 
    sof = $('#PrSoftware').val() /1 ; 
    har = $('#PrHardware').val() /1 ; 
    add = $('#PrAdditional').val() /1 ; 

    tot = dis + fre + pro + str + gro + sof + har + add; 
    $('#PrTotal').val(tot) ; // display the total 
}); 
+1

我認爲這億韓元」因爲在HTML中有'onkeyup ='calcCosting()「'不是'onkeyup =」calcCosting「',所以事件對象將會丟失。更新:使用JQuery綁定事件的版本是可以的。 – 2011-05-18 16:32:07

+0

你是完全正確的。我發佈了第二個例子,肯定會工作:-) – 2011-05-18 16:35:30

+0

是的,JS/Jquery內部的綁定事件比使用HTML屬性更好_style_ :) – 2011-05-18 16:37:46