javascript点击功能不能在多个按钮上工作

时间:2015-07-14 14:53:43

标签: javascript onclick

这是我的javascript代码。问题是只有最后一个创建函数正常工作但不是其他。例如,因为这里我有4个create()函数,只有最后一个正常工作。如果我有3,那么第3个将工作正常,但不是其他........请告诉我这个代码有什么问题....请帮助我对javasript新。

Please check my code in codepen here

window.onload=function()
{
var number_operation_table=document.getElementById('number_operation_table');


create('lt','<');
create('gteq','>=');
create('lteq','<=');
create('gt','>');


function create(prefix,operator)
{

number_operation_table.innerHTML+="<tr><td><input type='text' name='"+prefix+"_val1' id='"+prefix+"_val1'/>"+operator+"<input name='"+prefix+"_val2' type='text' id='"+prefix+"_val2'/></td>         <td><button id='check_"+prefix+"'>check</button></td>         <td id='"+prefix+"_result'></td>       </tr>";



 eval("var "+prefix+"check=document.getElementById('check_"+prefix+"');");
console.log(eval(prefix+"check"));
 console.log("button created with name:"+prefix+"check") ;

eval(prefix+"check.onclick=function()  {    calculate(prefix,operator);     };");


}

function calculate(prefix,operator)
{
var val1=parseInt((document.getElementById(prefix+'_val1')).value);
var val2=parseInt((document.getElementById(prefix+'_val2')).value);
var result_div=document.getElementById(prefix+'_result');



if((eval(''+val1+ operator +val2))==false)
  {

result_div.innerHTML="<span class='fail'>"+val1+ operator +val2 +" = false</span>";
  }

if((eval(''+val1+ operator +val2))==true)
  {
result_div.innerHTML="<span class='success'>true</span>";
   }

 }



};

1 个答案:

答案 0 :(得分:0)

您的问题(以及其他问题)是当您使用innerHTML连接到元素时,会销毁该元素内容上的所有事件侦听器。每次调用create时,您的代码都会破坏以前创建的所有onclick处理程序。

相反,请尝试:

var newRow = document.createElement("tr");
newRow.innerHTML = "<td><input type='text' name='"+prefix+"_val1' id='"+prefix+"_val1'/>"+operator+"<input name='"+prefix+"_val2' type='text' id='"+prefix+"_val2'/></td>         <td><button id='check_"+prefix+"'>check</button></td>         <td id='"+prefix+"_result'></td>";

number_operation_table.appendChild( newRow);

或者,您可以将一个事件侦听器附加到表,而不是每个按钮一个

其他问题:

你不应该需要&#39; eval&#39;完全按照create方法:

var myButton = document.getElementById('check_"+prefix+"');
myButton.onclick = function() { calculate( prefix, operator) };

您只需在计算方法中进行一次测试:

if((eval(''+val1+ operator +val2))==false) {
  result_div.innerHTML="<span class='fail'>"+val1+ operator +val2 +" = false</span>";
} else {

  result_div.innerHTML="<span class='success'>true</span>";
}