将 JavaScript 函数调用到 P 标签中

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

Calling JavaScript function into a P tag

javascript

提问by Adam

I would like to call the following javaScript function so it gets outputted to a HTML P tag, but am not sure how to do this without explicitly calling the function in the HTML file.

我想调用以下 javaScript 函数,以便将其输出到 HTML P 标记,但我不确定如何在不显式调用 HTML 文件中的函数的情况下执行此操作。

I do not want to do this...

我不想这样做...

<p class="showcode">
<script type="text/javascript">
    wise_words();
</script>
</p>

I would like to keep the javaScript code all in one js file.

我想将 javaScript 代码全部保存在一个 js 文件中。

I have tried it this way but this does not seem to work...

我已经尝试过这种方式,但这似乎不起作用......

document.getElementById("showcode").innerHTML = wise_words();

I would really appreciate any help as to what I am doing wrong.

我真的很感激任何关于我做错了什么的帮助。

Here is my code... http://codepen.io/anon/pen/qfLdEI would like to have the generated text get outputted inside the grey box.

这是我的代码... http://codepen.io/anon/pen/qfLdE我想让生成的文本在灰色框中输出。

回答by JLRishe

You should call the function in an onloadhandler, so that it is executed after the DOM has been constructed:

您应该在onload处理程序中调用该函数,以便在构造 DOM 后执行它:

window.onload = function() {
    document.getElementById("showcode").innerHTML = wise_words();        
}

Another problem is that your wise_words()function is using document.write(please don't use document.write) instead of returning a value. You need to return a value:

另一个问题是您的wise_words()函数正在使用document.write(请不要使用document.write)而不是返回值。您需要返回一个值:

var retText = wiseText[nextVal][0];

nextVal += 1;
writeCookie("wisewords", nextVal.toString(), 33);

return retText;

回答by SHEKHAR SHETE

Try following using Jquery:

尝试使用 Jquery 执行以下操作:

$(".showcode").html(wise_words());

NOTE:Assuming your function returns the HTML/text.

注意:假设您的函数返回 HTML/文本。

回答by 0xF

<p class="showcode">
    <script type="text/javascript">
        document.write(wise_words());
    </script>
</p>

or:

或者:

<body onload="document.getElementById('showcode').innerHTML = wise_words()">
    <p id="showcode">
    </p>
</body>

(note idinstead of class).

(注意id而不是class)。