怎么用js来修改href属性的值,暂时没学jq
修改了其中一段,见注释
function restoreMessage(){ var oldnode=document.getElementById("oldnode"); var newnode=document.createElement("b"); newnode.id="oldnode" //增加一个id,否则后面点击取不了值 newnode.innerHTML=oldnode.innerHTML; oldnode.parentNode.replaceChild(newnode,oldnode); var olda=document.getElementById("hah"); olda.innerHTML="将加粗改为斜体"; olda.setAttribute("href","javascript:replaceMessage()"); //这样写要加上javascript: }
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
</head>
<body>
<div><b id="oldnode">JavaScript</b>是一个很常用的技术,为网页添加动态效果。</div>
<a href="javascript:replaceMessage()" id="hah"> 将加粗改为斜体</a>
<script type="text/javascript">
function replaceMessage(){
var oldnode=document.getElementById("oldnode");
var newnode=document.createElement("i");
newnode.innerHTML=oldnode.innerHTML;
oldnode.parentNode.replaceChild(newnode,oldnode);
var olda=document.getElementById("hah"); //
olda.innerHTML="将斜体改为加粗";
//olda.href = olda.href.replace("replaceMessage()", "restoreMessage()");
olda.setAttribute("href","restoreMessage()");
}
function restoreMessage(){
var oldnode=document.getElementById("oldnode");
var newnode=document.createElement("b");
newnode.innerHTML=oldnode.innerHTML;
oldnode.parentNode.replaceChild(newnode,oldnode);
var olda=document.getElementById("hah"); //
olda.innerHTML="将加粗改为斜体";
//olda.href = olda.href.replace("restoreMessage()", "replaceMessage()");
olda.setAttribute("href","replaceMessage()");
}
</script>
</body>
</html>
在console上面写的,就这个页面 document.getElementsByTagName("div")[0].setAttribute("href","hello") //undefined document.getElementsByTagName("div")[0] //<div id="header" href="hello">…</div>
href.replace(/default/, "test")不会改变href本身,返回值才是处理后的结果
例:
<head>
<link media="screen" type="text/css" href="default/style.css" rel="stylesheet"/>
</head>
<body>
<div>
<script>
window.onload = function(){
var link = document.getElementsByTagName("link")[0];
link.href = link.href.replace("/default/", "/test/");
alert(document.getElementsByTagName("link")[0].href);
}
</script>
</div>
</body>
XXX.setAttribute("href","xxx")或者XXX.href="xxx"