将 HTML 字符串传递给 JavaScript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18515225/
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-27 12:14:27  来源:igfitidea点击:

Passing HTML string to JavaScript function

javascripthtml

提问by Adam Selene

I have a value that I'm currently accessing and passing to a JavaScript function through an onclick.

我有一个当前正在访问并通过 .js 文件传递​​给 JavaScript 函数的值onclick

<a href="#" onclick="openTextWindow('<%=myVar.varDefinition.getText()%>');">Text</a>

An example value that I'd receive from the getTextmethod is shown below.

我从该getText方法收到的示例值如下所示。

<h1>My Header</h1><br />My text

This value is then passed to my openTextWindowmethod.

然后将此值传递给我的openTextWindow方法。

function openTextWindow(inText) {
    myWindow = window.open('','','width=500, height=300');
    myWindow.document.write(inText);
    myWindow.focus();
}

For some reason, the value stored in inTextdoesn't match the string with HTML tags that I showed above. It ends up looking like this.

出于某种原因,存储在的值inText与我上面显示的带有 HTML 标记的字符串不匹配。它最终看起来像这样。

"<lt/>h1<gt/>My Header<lt/>/h1<gt/><lt/>br /<gt/>My text

When inTextis written to myWindow, I want that new window to render with the text My Headerwithin a styled header and My texton a line below that. I've tried replacing and escaping characters with no luck. Any ideas on how to fix this or a better way to accomplish what I'm trying to do? Thanks!

inText写到myWindow,我想新的窗口与文本渲染My Header一个风格的标题内,并My text在低于该线。我试过在没有运气的情况下替换和转义字符。关于如何解决这个问题或更好的方法来完成我想要做的事情的任何想法?谢谢!

采纳答案by Diodeus - James MacFarlane

You can stash your HTML in a hidden DIV or textarea, then grab that from your function instead of trying to pass it inline.

您可以将 HTML 存储在隐藏的 DIV 或 textarea 中,然后从您的函数中获取它,而不是尝试将其内联传递。

<a href="#" onclick="openTextWindow('DIV1');">Text</a>
<div id="DIV1" style="display:none"><%=myVar.varDefinition.getText()%></div>

JS:

JS:

function openTextWindow(divName) {
    var inText = document.getElemenyById(divName).innerHTML;
    myWindow = window.open('','','width=500, height=300');
    myWindow.document.write(inText);
    myWindow.focus();
}