开发者

HTML onload - using variables as parameters

I want to use something like:

<body onLoad="init('A sentence with "quoted text" as parameter')">

Unfortunately, this does work, as the quotes in the parameter are not treated properly.

Escaping the quotes also does not work

<body onLoad="init('A开发者_如何学JAVA sentence with \"quoted text\" as parameter')">

(Above also does not work).

How do I deal with this. I though maybe I can create a string variable and assigne my sentence (with quotes) to it. But I dont know how to do it! The body onload is HTML and the Javascript variables would be visible only within the scope of the script, right? To be precise, the following does not work:

<script language="JavaScript">
var dada='A sentence with \"quoted text\" as parameter';
</script>
<body onLoad="init($dada, '</a>')">


You would have to use HTML entities to make it work:

<body onLoad="init('A sentence with &quot;quoted text&quot; as parameter')">

the much cleaner way, though, would be to assign the value in a separate <SCRIPT> part in the document's head.

...
<script>
body.onload = function() { init('A sentence with "quoted text" as parameter'); }
</script>
<body>
...

the onload event has the general downside that it is fired only when the document and all its assets (images, style sheets...) have been loaded. This is where the onDOMLoad event comes in: It fires when the core HTML structure is ready, and all elements are rendered. It is not uniformly supported across browsers, though, so all frameworks have their own implementation of it.

The jQuery version is called .ready().


Rather than inlining the onLoad method, why not set it programatically. You can then use the power of closures to get the data into the function.

<script type="text/javascript">
var data = "some data";
document.body.onload = function()
{
    alert(data);
}
</script>


not the nicest way

onload='init("A sentence with \"quoted text\" as parameter")'


By the way, I was making a silly mistake.

<script language="JavaScript"> 
var dada='A sentence with \"quoted text\" as parameter'; </script> 
<body onLoad="init(dada, '</a>')"> 

This works too. I was using $dada instead of dada in the onload call.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜