Trying to call a function in javascript
This is my code all I need to do is call a function which will write the contents to a dynamic div
<script language='javascript' type='text/javascript'> function getComments(id) { alert(id); } var resultSet=""; function CreateDiv() { resultSet+="<br/><div id='"+rows.data[i].id+"'></div><script language='javascript' type='text/javascript'> getComments("+rows.data[i].i开发者_运维知识库d+"); <\/script>"; } window.onload=CreateDiv; </script>
The function getComments is not being called at all
What's that I am missing here
There are a few problems there.
- You're referencing
rows
without defining it anywhere, which will cause an exception. - Assuming you define
rows
somewhere you haven't shown, the code's just creating a string containing ascript
tag and putting that string inresultSet
. To cause the code inside the script tag to run, you'd have to assignresultSet
toinnerHTML
on some element. - There's an extra
)
in your call togetComments
within the generated script.
Separately: Your id
values would appear to be numbers (this is based on your passing them into getComments
with no quotes around them). Note that using id
values starting with a digit is allowed in HTML5, but not in earlier versions of HTML and not in CSS, so it's probably best avoided.
There's almost certainly a better way to do what you're actually trying to do, you may consider a separate question outlining the goal, how you've approached it so far, and asking for alternatives.
I would suggest that you break the code down into steps while you debug it. Specifically where you populate resultSet. Break it down at each plus sign. Then you can step through it and see how it is being populated.
resultSet+="<br/><div id='";
resultSet+=rows.data[i].id;
and so on.
Secondly, have a look in View Source to see what this looks like on the page when you run it. Does the HTML look properly formed?
Also, I am questioning whether that final <\/script>
in resultSet is correct.
Try replacing the createDiv
function with this:
function CreateDiv(){
resultSet += "<br/><div id='"+rows.data[i].id+"'></div>" + getComments(rows.data[i].id);
}
It should work flawlessly.
精彩评论