Problem with using javascript to insert <input> tags in html
I am trying to take text that is in an array (one word per value) and insert it into html. All the code is here: http://jsfiddle.net/chromedude/r6wVq/3/.
Update: My question is what am I doing wrong? It does not do anything which is weird.
Just for everybody who was wondering what this code is supposed to help me do is memorize long passages for school.开发者_如何学Go
You have an infinite loop, that's why the browser crashes:
for (i = 0; i < text.length; i++) {
var currentText = text[i];
for (i = 0; i<blanks.length; i++){}
}
The second loop always resets the counter variable i
to 0
. If you have nested loops you have to use different variables. And use var
to declare the variables as local, e.g.
for (var i = 0; i < text.length; i++) {
var currentText = text[i];
for ( var j = 0; j<blanks.length; j++){
}
}
Same for your most outer for
loop!
I don't know exactly what you want to achieve with the code, but here are some comments:
var blankNum = Math.random(Math.floor() * (text.length / 2));
Math.random
takes no parameter, but Math.floor
does.
for (i = 0; i < blanks.length; i++) {
blanks
is still empty at this point, so the loop will never run.
if (currentText==blanks[i]){
Are you sure that blanks[i]
will contain text? The previous mentioned (never running) loop seems to add numbers to the array.
textPrelim = <input type="text"></input>
You get a syntax error here, you must enclose the string into quotes.
I fixed your fiddle: http://jsfiddle.net/yEKPt/1/
What was wrong:
- for iterator scope (here)
This line (27) threw a syntax error:
textPrelim = <input type="text"></input> //Needs to be quoted.
Should be:
textPrelim = '<input type="text"></input>'; //Quoted.
You reversed Math.random and Math.floor (lines 8, 14). (See:
Math.Random()
,Math.Floor()
)var blank = Math.random(Math.floor() * (text.length / 2));
Check out my revised version. I think it accomplishes what you were looking for?
With addition to Felix's answer, try to check your code at http://www.jslint.com for syntax errors and undeclared (implicitly global) variables.
精彩评论