简体   繁体   English

将JavaScript函数调用到P标记中

[英]Calling JavaScript function into a P tag

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/qfLdE I would like to have the generated text get outputted inside the grey box. 这是我的代码... http://codepen.io/anon/pen/qfLdE我想让生成的文本在灰色框内输出。

You should call the function in an onload handler, 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. 另一个问题是你的wise_words()函数正在使用document.write (请不要使用document.write )而不是返回一个值。 You need to return a value: 您需要返回一个值:

var retText = wiseText[nextVal][0];

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

return retText;

Try following using Jquery: 尝试使用Jquery:

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

NOTE: Assuming your function returns the HTML/text. 注意:假设您的函数返回HTML /文本。

<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 id instead of class ). (注意id而不是class )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM