Javascript onclick替换div内容的整个内部html

时间:2015-10-13 03:36:24

标签: javascript replace onclick innerhtml

当他们点击剧院时,它应该在新的功能到位时改为NORMAL

示例来自:



<div id="links">
<a onClick="refreshStream()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; REFRESH</a>
<a onClick="TheaterMode()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; THEATER</a>
</div> 
&#13;
&#13;
&#13;

TO:

&#13;
&#13;
<div id="links">
<a onClick="refreshStream()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; REFRESH</a>
<a onClick="normalsize()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; NORMAL</a>";
</div> 
&#13;
&#13;
&#13;

我试过这个但是没有工作希望有人可以帮助你感谢。

&#13;
&#13;
<script>
document.getElementById("links").innerHTML = "<a onClick="refreshStream()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; REFRESH</a><a onClick="normalsize()" onmouseover="color:red;" style="cursor: pointer;" draggable="false" oncontextmenu="return false;">&nbsp;&nbsp; NORMAL</a>";
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我简化了你的例子。基本上,您需要将.innerHTML = ...中使用单引号分配的html包装起来,或者使用\来转义引号。

简化示例:

&#13;
&#13;
// escape quotes with backslash
function theaterMode() {
    document.getElementById("links").innerHTML = "<a onclick=\"refreshStream()\" style=\"cursor: pointer;\">&nbsp;&nbsp; REFRESH</a><a onclick=\"normalSize()\" style=\"cursor: pointer;\">&nbsp;&nbsp; NORMAL</a>";
}

// or wrap HTML with single quotes
function normalSize() {
    document.getElementById("links").innerHTML = '<a onclick="refreshStream()" style="cursor: pointer;">&nbsp;&nbsp; REFRESH</a><a onclick="theaterMode()" style="cursor: pointer;">&nbsp;&nbsp; THEATER</a>';
}

function refreshStream() {
    document.getElementById("links").innerHTML = "<a onclick=\"refreshStream()\" style=\"cursor: pointer;\">&nbsp;&nbsp; REFRESH</a><a onclick=\"normalSize()\"  style=\"cursor: pointer;\">&nbsp;&nbsp; NORMAL</a>";
}
&#13;
<div id="links">
    <a onclick="refreshStream()" style="cursor: pointer;">&nbsp;&nbsp; REFRESH</a>
    <a onclick="theaterMode()" style="cursor: pointer;">&nbsp;&nbsp; THEATER</a>
</div>
&#13;
&#13;
&#13;

有更简洁的方法可以做到这一点,如果你只是改变了第二个链接所做的事情,那么就没有理由继续更新第一个链接。

希望有所帮助。