我正在尝试在HTML页面上显示一些JavaScript变量。
我最初是使用document.write()
的,但是在调用该函数时,它用来覆盖当前页面。
经过四处搜寻后,人们普遍同意document.write()
不太受欢迎。还有哪些其他选择?
我找到了一个建议使用.innerHTML
的页面,但该页面写于2005年。
一个jsFiddle说明我的问题http://jsfiddle.net/xHk5g/
最佳答案
Element.innerHTML
几乎是要走的路。以下是使用它的几种方法:
的HTML
<div class="results"></div>
的JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
如果您只想更新
<div>
的一部分,我通常只添加一个空元素,并添加一个类似于value
的类,或者将一个内容替换为主<div>
。例如<div class="content">Hello <span class='value'></span></div>
然后,我将使用以下代码:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
然后,HTML/DOM现在将包含:
<div class="content">Hello <span class='value'>World!</span></div>
完整的例子。点击“运行摘要”进行尝试。
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>