JavaScript Functions are worth learning. This article will focus on the use of JavaScript anonymous functions in the loop structure. I believe you will be interested.
JavaScript anonymous functions in the Loop Structure
First look at the following code
- <SCRIPTLANGUAGESCRIPTLANGUAGE = "JavaScript">
- <! --
- FunctionDelete_Row (I)
- {
- Alert (I );
- }
- Functiontest ()
- {
- For (vari = 0; I <5; I ++)
- {
- Vartable11 = document. getElementById ("table11 ");
- Vartr11 = table11.insertRow ();
- Vartrstr = "tr" + tr11.rowIndex;
- Tr11.id = trstr;
- Tr11.ondblclick = function ()
- {
- Delete_Row (trstr );
- };
- Vartd11 = tr11.insertCell ();
- Td11.innerHTML = I;
- Td11 = tr11.insertCell ();
- Td11.innerText = "I Love You ";
- Td11 = tr11.insertCell ();
- Td11.innerText = "dumb ";
- Td11 = tr11.insertCell ();
- }
- }
- // -->
- </SCRIPT>
- <Tableidtableid = "table11" border = 1>
- <Tbody>
- <Tr>
- <Td> first column </td>
- <Td> second column </td>
- <Td> third column </td>
- </Tr>
- </Tbody>
- </Table>
- <Br>
- <Inputtypeinputtype = "button" value = "GO" onclick = "test ()">
-
After you click the button, five rows are inserted in Table 11. The double-click event of a row uses the JavaScript anonymous function.
Imagine what you will see when you click row 2nd and row 3rd. Will it be alert ('tr0') and alert ('tr1'), just like what you think?
Apparently it wasn't the result I wanted, but alert ('tr5') popped up. It was a bit strange! It is certain that the problem lies in the JavaScript anonymous function. It may be that the double-click event of this row points to the same JavaScript anonymous function. I don't know what you think?
If you change the above Code to the following code, you will get the expected result.
- <SCRIPTLANGUAGESCRIPTLANGUAGE = "JavaScript">
- <! --
- FunctionDelete_Row (I)
- {
- Alert (I );
- }
- Functiontest ()
- {
- For (vari = 0; I <5; I ++)
- {
- Vartable11 = document. getElementById ("table11 ");
- Vartr11 = table11.insertRow ();
- Vartrstr = "tr" + tr11.rowIndex;
- Tr11.id = trstr;
- Tr11.ondblclick = f (trstr );
- Vartd11 = tr11.insertCell ();
- Td11.innerHTML = I;
- Td11 = tr11.insertCell ();
- Td11.innerText = "I Love You ";
- Td11 = tr11.insertCell ();
- Td11.innerText = "dumb ";
- Td11 = tr11.insertCell ();
- }
- }
- Functionf (I)
- {
- Return function ()
- {
- Delete_Row (I );
- }
- }
- // -->
- </SCRIPT>
- <Tableidtableid = "table11" border = 1>
- <Tbody>
- <Tr>
- <Td> first column </td>
- <Td> second column </td>
- <Td> third column </td>
- </Tr>
- </Tbody>
- </Table>
- <Br>
- <Inputtypeinputtype = "button" value = "GO" onclick = "test ()">
-