如何将包含 html 文本的字符串显示在 javascript 函数中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5968503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:58:49  来源:igfitidea点击:

How can I put a string containing html text to be displayed in a javascript function?

javajavascripthtml

提问by Vimal Basdeo

How can I put a string containing html text to be displayed in a JavaScript function?

如何将包含 html 文本的字符串显示在 JavaScript 函数中?

String test = "DisplayNext(\"String containing html tags\")";

String NextLink = "<br><a href='#' onclick="+test+"> Next</a>";

JavaScript function:

JavaScript 函数:

function DisplayNext(Next){
    alert(Next);
}

I want to pass html tags to a JavaScript function and display it using an alert box..How do I do that ??

我想将 html 标签传递给 JavaScript 函数并使用警告框显示它..我该怎么做?

回答by gilly3

You'll need to encode your html tags.

您需要对 html 标签进行编码。

>becomes &gt;
<becomes &lt;
"becomes &quot;

>变成&gt;
<变成&lt;
"变成&quot;

You'll also need to encode your JavaScript.

您还需要对 JavaScript 进行编码。

'becomes \'

'变成 \'

Then use single quotes to quote your JavaScript (so the double quotes don't close the onclick attribute prematurely):

然后使用单引号引用您的 JavaScript(因此双引号不会过早关闭 onclick 属性):

String test = "DisplayNext('" + encodedHTML + "')";
String nextLink = "<br /><a href="#" onclick=\"" + test + "\"> Next</a>";

回答by Lou Franco

Javascript alert boxes aren't HTML viewers. You can try replacing your alert calls with this:

Javascript 警报框不是 HTML 查看器。你可以尝试用这个替换你的警报电话:

http://plugins.jquery.com/plugin-tags/messagebox

http://plugins.jquery.com/plugin-tags/messagebox