栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在没有document.write的情况下在HTML页面中显示JavaScript变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在没有document.write的情况下在HTML页面中显示JavaScript变量

Element.innerHTML
几乎是要走的路。以下是使用它的几种方法:

HTML

<div ></div>

Javascript

// 'Modern' browsers (IE8+, use CSS-style selectors)document.querySelector('.results').innerHTML = 'Hello World!';// Using the jQuery library$('.results').html('Hello World!');

如果您只想更新

<div>
I 的一部分,通常只需要添加一个类似
value
或类的空元素,就可以将main的内容替换为
<div>
。例如

<div >Hello <span ></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 >Hello <span >World!</span></div>

完整的例子。点击“运行摘要”进行尝试。

// Plain Javascript Examplevar $jsName = document.querySelector('.name');var $jsValue = document.querySelector('.jsValue');$jsName.addEventListener('input', function(event){  $jsValue.innerHTML = $jsName.value;}, false);// JQuery examplevar $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://pre.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  type="text" value="World"/></label>  <!-- Plain Javascript Example -->  <h1>Plain Javascript Example</h1>Hello <span >World</span>  <!-- jQuery Example -->  <h1>jQuery Example</h1>Hello <span >World</span></body></html>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614755.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号