如何在 HTML 中打印一个特定的 Javascript 变量?

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

How to print one specific Javascript variable in HTML?

javascripthtml

提问by user2979725

I want to ask how I can print a Javascript variable in HTML form (e.g. output it on the screen)?

我想问一下如何以 HTML 形式打印 Javascript 变量(例如将其输出到屏幕上)?

Here is my JS code:

这是我的 JS 代码:

<script type="text/javascript">
var howLongIsThis = myPlayer.duration();
</script>

This var howLongIsThis = myPlayer.duration();is Jquery variable!

var howLongIsThis = myPlayer.duration();是 Jquery 变量!

So how i can show this value in HTML page?

那么我如何在 HTML 页面中显示这个值呢?

回答by Moob

Set it to be the innerHTML or value of a html element:

将它设置为一个 html 元素的 innerHTML 或值:

var howLongIsThis = myPlayer.duration();
var displayEl = document.getElementById("duration");
displayEl.innerHTML = howLongIsThis;

or if you want in in a form field:

或者如果你想在表单字段中:

displayEl.value = howLongIsThis;

回答by Ryan Williams

Assuming you have a <div id="example"></div>somewhere in your HTML, you want to run JavaScript after the DOM has loaded which adds the value you want to that div. In jQuery (which you specified in your question you're using), this would simply be:

假设您<div id="example"></div>在 HTML 中的某个地方有一个,您希望在 DOM 加载后运行 JavaScript,将您想要的值添加到div. 在 jQuery(您在您使用的问题中指定)中,这将是:

$('div#example').html(myPlayer.duration());

Here's a fiddle: http://jsfiddle.net/RyanJW/QjXKL/2/

这是一个小提琴:http: //jsfiddle.net/RyanJW/QjXKL/2/

回答by Anand Jha

Try this,

尝试这个,

your HTML

你的 HTML

<input type="text" id="logId" />
<div id="logId1"></div>

js Script

js脚本

var howLongIsThis = myPlayer.duration();
document.getElementById("logId").value=howLongIsThis;
document.getElementById("logId1").innerHTML=howLongIsThis;

hope this will give you an idea to solve your problem

希望这会给你一个想法来解决你的问题