JS如何在页面中插入HTML代码

html-css016

JS如何在页面中插入HTML代码,第1张

步骤

1、新建一网页文件“sample.html",用记事本或其它文本编辑软件(如UltraEdit)打开,输入如图所示的HTML代码。该网页文件包括一个蓝色的字符串,一个按钮和一个文本框。

2、JS代码可插入到”head"标签之间。编写Javascript代码,代码内容如图所示,并将该段代码复制到网页文件”sample.html“中标签”<head>"和“</head>之间,然后查看网页文件的显示内容。

<!DOCTYPE html>

<html>

<head>

<script src="jquery.js"></script>

<div id="dictionary">

</div>

<div class="letters">

<div class="letter" id="letter-a">

<h3><a href="entries-a.html">A</a></h3>

</div>

<div class="letter" id="letter-b">

<h3><a href="entries-a.html">B</a></h3>

</div>

<div class="letter" id="letter-c">

<h3><a href="entries-a.html">C</a></h3>

</div>

<div class="letter" id="letter-d">

<h3><a href="entries-a.html">D</a></h3>

</div>

<!-- and so on -->

</div>

</head>

<body >

<script>

$(document).ready(function() {

$('#letter-c a').click(function(event) {

event.preventDefault()

$.getScript('c.js')

})

})

</script>

</body>

</html>

将写好的c.js文件放置同一个目录下面

var entries = [

{

"term": "CALAMITY",

"part": "n.",

"definition": "A more than commonly plain and..."

},

{

"term": "CANNIBAL",

"part": "n.",

"definition": "A gastronome of the old school who..."

},

{

"term": "CHILDHOOD",

"part": "n.",

"definition": "The period of human life intermediate..."

}

//省略的内容

]

var html = ''

$.each(entries, function() {

html += '<div class="entry">'

html += '<h3 class="term">' + this.term + '</h3>'

html += '<div class="part">' + this.part + '</div>'

html += '<div class="definition">' + this.definition + '</div>'

html += '</div>'

})

$('#dictionary').html(html)

//$('#dictionary').append(html)

这里的$('#dictionary').html(html)可以直接将需要的代码放入到指定的div内  (<div id="dictionary">)

也可以通过$('#dictionary').append(html)将代码附加到指定的div内  (<div id="dictionary">)

一、使用javascript 模板引擎

用javascript预编译模版,就是动态修改模板文件使之成为一个可用的静态HTML文件。 我平时会使用artTemplate,性能很好而且易上手。

编写模板

使用一个type="text/html"的script标签存放模板:

<script id="test" type="text/html">

<h1>{{title}}</h1>

<ul>

    {{each list as value i}}

        <li>索引 {{i + 1}} :{{value}}</li>

    {{/each}}

</ul>

</script>

渲染模板

var data = {

    title: '标签',

    list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']

}

var html = template('test', data)

document.getElementById('content').innerHTML = html

二、使用CoffeeScript

CoffeeScript支持类似于Python的跨行字符串,这样很轻易的就能保持HTML结构的可读性,而不需要使用“+”或者采用拼数组的形式。

str="""

<div class="dialog">

  <div class="title">

    <img src="close.gif" alt="关闭" />关闭

  </div>

  <div class="content">

    <img src="delete.jpg" alt="" />

  </div>

  <div class="bottom">

    <input id="Button2" type="button" value="确定" class="btn"/>&nbsp&nbsp

    <input id="Button3" type="button" value="取消" class="btn"/>

  </div>

</div>

"""