简体   繁体   中英

How to Ignore HTML Tags when Using document.write

I have this line of Javascript code that is supposed to show the line

document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");

This is done by using document.write . So it is basically

document.write("document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");");

Firstly, I pass the above string to an array, and then later on in the program display it using document.write .

The problem is that when display it, it actually makes a text box and shows it. I believe this is happening because HTML just goes through and checks for tags, regardless of their position in quotes, etc.

How do I fix this? I just want to display the actual line, not the output from the line. Is there anyway to do this? Can I use something different than document.write ? Can I output it to a text box that simply display it? Is that enough?

You need to escape the tags. These symbols: < > must be encoded as &lt; &gt; .

Your example should be similar to this:

document.write(" `&lt;textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\"&gt;");

Replace < by &lt; and > by &gt;

Try this :

 document.write("document.write(\\" &lt;textarea name='Text1' cols=\\"+col+\\" rows=\\"+row+\\" id='textbox' style='HelveticaNeue-Light'&gt;\\");"); 

You can add your string directly to an element by setting its innerText :

var myDiv = document.getElementById('myDiv');
myDiv.innerText = '<p>These p tags will be displayed as text</p>';

您对它进行HTML编码,就像这样

document.write("document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");".replace('<', '&lt;').replace('>', '&gt;'));

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