发布者:admin 发布时间:2010-7-31 所属栏目:网络基础
摘要:
IE的DHTML对象提供了四个可读写的属性来动态操作页面元素的内容:innerText, outerText, innerHTML, outerHTML. 其中innerText,outerText属性的值是作为普通文本呈现的,即使它含有HTML标签也如实反应出来;而innerHTML, outerHTML呈现的是经HTML引擎解析后文本,它可以反应属性中HTML标签的表现效果。 对对象的outerText,outerHTML属性赋值(即写操作)会删除该对象
在页面中指定元素相关位置新增文本内容,需采用insertAdjacentHTML和insertAdjacentText方法,形式如下:
object.insertAdjacentText(sWhere, sText)
object.insertAdjacentHTML(sWhere, sText)
其中 sWhere 表示插入的文本相对于html标签的位置,有如下四个预设值: beforeBegin,afterBegin,beforeEnd,afterEnd,示例如下:
------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script language="javascript">
var i=0;
function insertTextDemo(obj)
{
//beforeBegin,afterBegin,beforeEnd,afterEnd
obj.insertAdjacentText("afterBegin","afterBegin");
obj.insertAdjacentText("beforeBegin","beforeBegin");
obj.insertAdjacentText("beforeEnd","beforeEnd");
obj.insertAdjacentText("afterEnd","afterEnd");
}
function insertHTMLDemo(obj)
{
i = i+1;
var insString = '<input type="text" id="txt'+i+'" /><br />';
obj.insertAdjacentHTML("afterBegin",insString);
obj.insertAdjacentHTML("beforeBegin","<b>beforeBegin</b>");
obj.insertAdjacentHTML("beforeEnd","<b>beforeEnd</b>");
obj.insertAdjacentHTML("afterEnd","<b>afterEnd</b>");
}
function disPlay()
{
var txt = document.getElementsByTagName("input");
for(var i=0; i<txt.length; i++)
{
tmp = txt[i];
if(tmp.type=="text")
{
alert(tmp.value);
}
}
}
function outerReplace(divContent)
{
divContent.outerHTML = "<b>sdlfsd</b>";
}
</script>
</HEAD>
<BODY>
<form id="fromDemo" name="fromDemo">
<div>
<input type="button" value="innerText" onclick="alert(divContent.innerText)" />
<input type="button" value="outerText" onclick="alert(divContent.outerText)" />
<input type="button" value="innerHTML" onclick="alert(divContent.innerHTML)" />
<input type="button" value="outerHTML" onclick="alert(divContent.outerHTML)" />
<hr />
<input type="button" value="insertText" onclick="insertTextDemo(divContent)" />
<input type="button" value="insertHTML" onclick="insertHTMLDemo(divContent)" />
<hr />
<input type="button" value="outerReplace" onclick="outerReplace(divContent)" />
<input type="button" value="DisplayAllText" onclick="disPlay()" />
</div>
<div id="divContent">
<div>Text:<input type="text" name="txtUserName" /></div>
</div>
</form>
</BODY>
</HTML>
页面内容动态操作还需要注意如下一些细节:
1.只有文档BODY内显示的内容能被以上属性和方法动态改变,BODY对象的内容能被动态操作,但BODY对象本身无法被替换。
2.以上属性和方式不能操作空标签(没有内容的html标签),如input,img。
3.对于table对象而言,只有td(innerHTML/innerText)和table(outerHMTL/outerText)对象可以用某些属性来替换或插入内容;而其他table对象,如tr、tbody不能用这些属性来改变内容。
评价等级:0 用户对这篇文章进行评级
阅读次数:这篇文章已被阅读 151 次
标签: 北大青鸟名师
您如何评价这篇新闻?