<a> tag problem while generating javascript through java code
How should I write a statement in Java to produce JavaScript in a page
out.write("document.write('< a href='str'> '+str.slice(beg+1,end)+' </a>');");
so that it will create statement in Java开发者_如何学CScript
document.write("< a href=' "+str+" '> "+str.slice(beg+1,end)+" </a>"); //< a
and the link will go to page whose address is stored in str
curently it is taking href value as str and not the value stored in str i.e. it is searching for page str
out.write("document.write(\"< a href='\" + str + \"'> \" + str.slice(beg + 1, end) + \" </a>\");");
You're not closing the <a>
tag!
document.write("<a href='" + str + "'>" + str.slice(beg+1, end) + "</a>");
out.write("document.write('<a href='str'> '+str.slice(beg+1,end)+' </a>');");
Ouch, you've got four levels of string encoding here — no wonder it's confusing you. You've got a text string inside an HTML text node inside a JavaScript string literal inside an HTML <script>
block inside a Java string literal.
It's really best to avoid doing stuff like this because it's so easy to get wrong. You're missing +
to join str to the string inside the attribute value; if str
contains a <
or &
you've got a problem due to the embedding in HTML (potentially causing cross-site scripting security holes); if str
contains a space or quotes you've got a problem due to the embedding in an attribute value; the </
sequence is invalid HTML inside a <script>
block...
Whilst you can fix this by hacking up your own string escape functions, I'd say you're better off using functions that don't involve bodging strings together:
out.write(
"var link= document.createElement('a');\n"+
"link.href= str;\n"+
"link.appendChild(document.createTextNode(str.slice(beg+1, end)));\n"+
"document.getElementById('foo').appendChild(link);\n"
);
Where foo
is the element where you want the link to appear.
精彩评论