Javascript why isnt this simple counter working in my loop

为君一笑 提交于 2019-12-10 11:57:42

问题


I have a function that is called button and it appends m table using a loop. I have modified the loop so that it assigns an ID to each <td> it makes. However, it does not seem to be working right.

Here it is in action, follow the use case below to test it: http://jsfiddle.net/JEAkX/19/

Here is a simple use case I use to test it:

  1. Change the letter in a cell
  2. Press "More"
  3. Change the letter in one of the new cells

It should function the same as the original cells if the ID was getting assigned properly.

The counter is: var n = 13;

and it is inserted into the appended cell as such:

cell.innerHTML = "<input type='text' id='r"+ (n) +"' size='1' onChange='getPos('r"+ (n++) +"'), modifyCells('alphabetTable')' value='" + subset[i++] + "' />"`

This is the DOM source I am getting:

<td><input id="r13" size="1" onchange="getPos(" r14="" ),="" modifycells(="" alphabettable="" )="" value="q" type="text"></td>
<td><input id="r14" size="1" onchange="getPos(" r15="" ),="" modifycells(="" alphabettable="" )="" value="r" type="text"></td>

I suspect it has to do with cramming everything into 1 line like @zzzzBov said but I dont know how else to do it.


回答1:


Besides the n++, there's a quoting issue in your HTML. There are nested single quotes in the onchange attribute, like so:

<input type='text' id='r19' size='1' onChange='getPos('r20'), modifyCells('alphabetTable')' value='p' />

Quick fix for the syntax is to use escaped double quotes, so you can get going: cell.innerHTML = "<input type='text' id='r"+ n +"' size='1' onChange='getPos(\"r"+ (n++) +"\"), modifyCells(\"alphabetTable\")' value='" + subset[i++] + "' />"




回答2:


Separation of HTML/CSS/JS notwithstanding.... You need 3 levels of quotes. Also, the comma in the onclick event needs to be a semicolon.

Perhaps:

cell.innerHTML = "<input type='text' id='r" + n + "' size='1'
  onChange='getPos(\"r" + (n++) + "\"); modifyCells(\"alphabetTable\")'
  value='" + subset[i++] + "' />"


来源:https://stackoverflow.com/questions/5255403/javascript-why-isnt-this-simple-counter-working-in-my-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!