HTML onload - using variables as parameters

自作多情 提交于 2019-12-22 13:57:32

问题


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 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>')">

回答1:


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().




回答2:


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>



回答3:


not the nicest way

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



回答4:


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.



来源:https://stackoverflow.com/questions/4003345/html-onload-using-variables-as-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!