html中怎样插入html代码

html-css07

html中怎样插入html代码,第1张

在JS中插入短的HTML代码,可以通过先使用一个函数来包着,你要添加的HTMl代码,然后在使用innerHTML这个函数提取就行,在你的HTMl中添加一个事件就行,然后调用这个函数就行了,具体的我提供例子给你看下:

<html>

<head>

<script>

function insert(){

var insertText = "<table><tr><td>any thing</td></tr></table>"

document.getElementById("insert").innerHTML(insertText)

}

</script>

</head>

<body>

<button onclick="insert()">Insert</button>

<div id="insert"></div>

</body>

</html>

1、J首先输入s_file01.js,//程序代码 document.write(" <script language=\"javascript\" src="\/com\/ Js_file02.js \" ><\/script>")。

2、 html代码 代码如下:<html> <body> <input type="button" value="ok" onclick="javascript:fun_b()"> </body> //必须在这个位置,也即<body>...</body>之下: <script language="JAVASCRIPT" src='Js_b.js'></script> </html>。

3、Js_file01.js 代码如下://程序代码 document.scripts[0].src=" Js_file02.js"。

4、看到自己的JS文件。

5、可以看到js插入成功了。

<!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">)