问题
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:
- Change the letter in a cell
- Press "More"
- 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