JavaScript:
document.getElementById("myId").setAttribute("href","www.xxx.com");
document.getElementById("myId").href = "www.xxx.com";
JQuery:
$("#myId").attr("href","www.xxx.com");
例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing</title>
</head>
<script type="text/javascript" src="example.js">
</script>
<body>
<div id="testdiv">
</div>
</body>
</html>
example.js
window.onload = function() {
var testdiv = document.getElementById("testdiv");
testdiv.innerHTML="<p>I inserted <em>this</em> content.</p>";
}
另一种方法
window.onload = function() {
var para = document.createElement("p");
var txt1 = document.createTextNode("I inserted ");
var emphasis = document.createElement("em");
var txt2 = document.createTextNode("this");
var txt3 = document.createTextNode(" content.");
para.appendChild(txt1);
emphasis.appendChild(txt2);
para.appendChild(emphasis);
para.appendChild(txt3);
var testdiv = document.getElementById("testdiv");
testdiv.appendChild(para);
}
这与在DIV内动态载入另一个页面非常相似!
补充把元素插入到指定元素的前边:
document.getElementById("msgplan").innerHTML=newmsg;
改成
document.getElementById("msgplan").innerHTML += newmsg;
或
document.getElementById("msgplan").innerHTML = newmsg + document.getElementById("msgplan").innerHTML;
一个是新消息放在前面,一个是新消息放后面
另一种方法:
<script type="text/javascript">
var authorized = localStorage.getItem('authorized');
if( authorized != 1 ){
var welcome_or_login_div = document.getElementById('welcome_or_login_div');
var contact_customer_service_separate = document.getElementById('contact_customer_service_separate');
var login_link = document.createElement("a");
login_link.href="/user/login/";
login_link.innerHTML=' 登录 ';
var glyphicon_vertical = document.createElement('span');
glyphicon_vertical.setAttribute('class', 'glyphicon glyphicon-option-vertical');
glyphicon_vertical.setAttribute('aria-hidden','true');
var register_link = document.createElement("a");
register_link.href="/user/register/";
register_link.innerHTML=' 注册 ';
welcome_or_login_div.insertBefore(login_link, contact_customer_service_separate);
welcome_or_login_div.insertBefore(glyphicon_vertical, contact_customer_service_separate);
welcome_or_login_div.insertBefore(register_link, contact_customer_service_separate);
}
else{
var welcome_or_login_div = document.getElementById('welcome_or_login_div');
var contact_customer_service_separate = document.getElementById('contact_customer_service_separate');
var welcome_message = document.createElement('span');
welcome_message.innerHTML = '你好 '+localStorage.user_name+',';
welcome_or_login_div.insertBefore(welcome_message, contact_customer_service_separate);
var logout_link = document.createElement("a");
logout_link.href="/user/logout/";
logout_link.innerHTML='退出';
welcome_or_login_div.insertBefore(logout_link, contact_customer_service_separate);
}
</script>