简体   繁体   中英

Javascript why isnt this simple counter working in my loop

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.

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++] + "' />"

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++] + "' />"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM