2011-05-18 31 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