【问题标题】:Javascript onclick replace entire inner html of div contentJavascript onclick 替换 div 内容的整个内部 html
【发布时间】:2016-01-10 16:09:15
【问题描述】:

当他们点击 THEATER 时,它应该会变为 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> 

到:

<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> 

我试过了,但是没用,希望有人能帮忙谢谢。

<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>

【问题讨论】:

  • refreshStreamTheaterMode 在哪里

标签: javascript replace onclick innerhtml


【解决方案1】:

我稍微简化了你的例子。基本上你要么需要用单引号将你在.innerHTML = ... 中分配的html 包裹起来,要么使用\ 来转义引号。

简化示例:

// 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>";
}
<div id="links">
    <a onclick="refreshStream()" style="cursor: pointer;">&nbsp;&nbsp; REFRESH</a>
    <a onclick="theaterMode()" style="cursor: pointer;">&nbsp;&nbsp; THEATER</a>
</div>

有更简洁的方法可以做到这一点,如果您只是更改第二个链接的功能,那么真的没有理由继续更新第一个链接。

希望对您有所帮助。

【讨论】:

  • 非常感谢您花时间解释事情。一旦我了解了单引号或使用 \ 来转义引号,一切对我来说变得如此清晰。 (JS新手)
  • 没问题,很高兴您从中获得了一些价值!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 1970-01-01
相关资源
最近更新 更多