简体   繁体   中英

how to pass as parameter to JS function from HTML large chunk of HTML code?

I want to pass as argument a large (maybe 2-3 paragraphs of html formatted code) chunk of HTML code to a Javascript function call from HTML. The problem is, the formatted HTML keeps appearing in the page itself, which shouldnt be the case ! I am assuming theres some problem with single/double quotes !

And, I am working on Facebook tab page.

Can anyone please help me ?

Thanks.

- ahsan

One way is to have a hidden div (something with display:none), and populate that with your 2-3 paragraphs of html formatted code. Then, you can just pass the innerHTML of the div into your function. Quotes (of any kind) won't cause a problem in this method.

Some libraries like icanhaz.js also do something like this:

<script type="text/html" id="someHTMLTemplate">
   <div>You can put whatever html you want here</div>
   <p>And the browser just ignores it</p>
</script>

I use the same technique with mustache.js and then grab the template from the innerHTML of the script tag after grabbing it by the dom id. This has the advantage that the browser doesn't have to parse your extra html while loading it is just parsed when you need to display it in another node on the page.

Another way is to encode the HTML and then decode it in the JS. Here's an example using the JS escape info:

console.log(escape("<hello></hello>"));           // %3Chello%3E%3C/hello%3E
console.log(unescape("%3Chello%3E%3C/hello%3E")); // <hello></hello>

Mind you, if you have an issue with your string quotations to begin with, then there will still be a problem encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM