Sea*_*yre 3 html javascript iframe
我有一个相当简单的页面,其中包含侧边栏导航和用于加载内容的iFrame.
我想通过单击侧栏导航中的链接来更改iFrame的内容.我正在使用javascript来更改document.element的源(.src).
我已经阅读了很多文章(StackOverflow)并且代码应该可以工作,但事实并非如此.
下面的代码是我创建的html页面,它包含标签中的JS.
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="css/default.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function getContent{
document.getElementById("contentFrame").src="LoremIpsum.html";
}
</script>
</head>
<body>
<div class="sidebar"><h1>Technical Documentation</h1>
<ul>
<li>Configuration Guides</li>
<li>API Guides</li>
<li><a href="" onclick='getContent()'> LoremIpsum</a></li>
</ul>
<!-- <button onclick="getContent()">Lorem Ipsum</button> -->
</div>
<iframe class="content" id="contentFrame" src="dummy.html">
</iframe>
</body>
Run Code Online (Sandbox Code Playgroud)
Sco*_*cus 16
您的问题是您忘记()
在功能名称后添加.
除此之外,还有一些其他要纠正的事情:
不要使用内嵌HTML事件属性(onclick
,onmouseover
等等),因为它们:
this
回调函数中的绑定.相反,在JavaScript中完成所有工作并用于.addEventListener()
设置事件处理程序.
当按钮(或其他元素)执行时,请勿使用超链接.如果您确实使用了超链接,则需要禁用其本机导航功能,这通过将href
属性设置为而#
不是""
.
// Place this code into a <script> element that goes just before the closing body tag (</body>).
// Get a reference to the button and the iframe
var btn = document.getElementById("btnChangeSrc");
var iFrame = document.getElementById("contentFrame");
// Set up a click event handler for the button
btn.addEventListener("click", getContent);
function getContent() {
console.log("Old source was: " + iFrame.src);
iFrame.src="LoremIpsum.html";
console.log("New source is: " + iFrame.src);
}
Run Code Online (Sandbox Code Playgroud)
<div class="sidebar"><h1>Technical Documentation</h1>
<ul>
<li>Configuration Guides</li>
<li>API Guides</li>
</ul>
<button id="btnChangeSrc">Change Source</button>
</div>
<iframe class="content" id="contentFrame" src="dummy.html"></iframe>
Run Code Online (Sandbox Code Playgroud)
您的函数声明中有语法错误(缺少括号):
function getContent {
document.getElementById("contentFrame").src="LoremIpsum.html";
}
Run Code Online (Sandbox Code Playgroud)
应该:
function getContent() {
document.getElementById("contentFrame").src="LoremIpsum.html";
}
Run Code Online (Sandbox Code Playgroud)
您还需要防止链接的默认事件
function getContent {
document.getElementById("contentFrame").src="LoremIpsum.html";
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2443 次 |
最近记录: |