开发者

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.

  1. You're referencing rows without defining it anywhere, which will cause an exception.
  2. Assuming you define rows somewhere you haven't shown, the code's just creating a string containing a script tag and putting that string in resultSet. To cause the code inside the script tag to run, you'd have to assign resultSet to innerHTML on some element.
  3. There's an extra ) in your call to getComments 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜