JavaScript function, pass HTML as parameter

I have two functions in my script, one that outputs some long HTML string, the other one that takes this string as a parameter and processes it.

function myFirstFunction() {
    //output some HTML
    return myHTML;
}

var myHTML = myFirstFunction();

function mySecondFunction(myHTML) {
    //do something with parameter
}

For some reason that I can't figure out, the Chrome JS Console keeps giving me the following error: "Uncaught SyntaxError: Unexpected token <"

I thought maybe that was due to the fact, that the outputed HTML was pretty long since it seems to be working with small chunks of HTML. Any thoughts? Thx!


Here's problem:

myHTML is a HTML string like this:

var myHTML ="<div id="foo"><div id='hello'>hello</div><div id="bar">bar'asdf'asf"sdf"&soidf;</div></div>";

That won't work because you have quotes and stuff inside it that are NOT escaped.

If you used innerHTML to get the HTML of an element on the page, this wouldn't be a problem.


myHTML是用一些<或>额外构造的,所以请验证html字符串


I'm assuming that you're literally trying to pass html, not in a string literal. If you try something like:

myFunction(<html><body>...);

That'll definitely through an error. You need to use string literals:

myFunction("<html><body>...");

If you're using html that has quotes in it, you need to escape them or use single quotes:

"<div id="name">" 

is not a valid string. Make it either:

"<div id="name">" or
'<div id="name">'
链接地址: http://www.djcxy.com/p/45956.html

上一篇: 用jquery插件提交表单

下一篇: JavaScript函数,将HTML作为参数传递