javascript - 捕获一系列 <input> 元素上的按键事件并对值求和

标签 javascript input keypress

我有一系列输入文本元素,其名称类似于 p_at[0][int]、p_at[1][int]、...。我需要为页面中的每个 input 捕获一个 onKeypress 事件以求和。 请注意,输入是动态生成的。我尝试以多种方式解决它,但对我没有任何帮助。

<input type="text"  value="1" name="p_at[0][65]">
<input type="text"  value="1" name="p_at[0][66]">
<input type="text"  value="1" name="p_at[0][67]">
<input type="text"  value="1" name="p_at[0][68]">
<input type="text"  value="1" name="p_at[0][69]">
    <input type="text"  value="0" name="sum[0]">
<input type="text"  value="1" name="p_at[1][65]">
<input type="text"  value="1" name="p_at[1][66]">
<input type="text"  value="1" name="p_at[1][67]">
<input type="text"  value="1" name="p_at[1][68]">
<input type="text"  value="1" name="p_at[1][69]">
     <input type="text"  value="0" name="sum[1]">

最佳答案

没有 jQuery 答案

var inputlist = document.getElementsByTagName('input');

var inputListener = function (evt) {
    //put the code that handles the event here
};

for( var i = 0; i < inputlist ){
    if( inputlist[i].type === "text" && inputlist.name.substr(0,4) === "p_at" ){
        if (elem.addEventListener)  // W3C DOM
            elem.addEventListener("Keypress",inputListener ,false);
        else if (elem.attachEvent) { // IE DOM
            elem.attachEvent("onKeypress", inputListener );
    }
    }
}

使用 jQuery Answer

$('input[type="text"][name^="p_at"]').keypress(function(evt){
    //put the code that handles the event here
});

关于javascript - 捕获一系列 &lt;input&gt; 元素上的按键事件并对值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618961/

相关文章:

html - 在黑莓上垂直对齐 html 输入文本

Javascript e.keyCode 无法捕获 IE 中的 Backspace/Del

javascript - Dropzone - Uncaught Error : No URL provided

javascript - HighCharts图表导出(截图下载)不显示Navigator图

javascript - 如何用JavaScript写入txt文件

java - 是否可以使用字符串作为计算?

vb.net - 在VB 2013中,有没有办法区分键盘输入和扫描仪输入?

javascript - 如何防止文本区域中的换行符并阻止 Jquery 将换行符计为值

javascript - iPhone上的pageshow事件仅触发一次

javascript - 浏览器支持的所有 HTML 标签