我有一个按钮,我试图让它根据选择框中的选项将html插入到列中。我已经查看了我的代码十几次并且无法理解为什么它的行为方式如下:而不是将代码插入div并显示它我被重定向到另一个网页“... / newlsetters-%newsletteryear %”。不确定是什么让这种情况发生。任何帮助将不胜感激!
<h1>KMVCSS Newsletters</h1> <h1 style="font-weight: 100">2014 - 2017</h1>
<div class="n-body">
<form>
<select id="nbox" name="newsletters">
<option value="2017">Newsletter 2017</option>
</select>
<button id="nbutton" onclick="displayNewsletter();">Get Newsletter
Link</button>
</form>
<div class="n-row">
<div id="col">
</div>
</div>
</div>
<script>
function displayNewsletter() {
var selectedNewsletter = document.getElementById("nbox").value;
var col= document.getElementById("col");
var a = "<h2>2017</h2> <img alt='newsletter' src='http://clone.kmvcss.org/wpcontent/themes/nu2013/images/2017-Newsletter.png' width='60px' height='180px'/> <a href='https://drive.google.com/open?id=0B0vGa180vtK9aDlPZlFIMTRmcDJvZ0l5Ti1WMGxIV3RMV3RV'>";
if (selectedNewsletter === "2017") {
col.innerHtml = a;
}
</script>
答案 0 :(得分:4)
<button id="nbutton" type='button' onclick="displayNewsletter();">Get Newsletter
Link</button>
默认情况下,它是一个提交按钮,浏览器执行表单提交,后续重定向到表单中指定的url
(在您的情况下,它是空的)。
答案 1 :(得分:1)
您需要在函数中添加return false
<h1>KMVCSS Newsletters</h1> <h1 style="font-weight: 100">2014 - 2017</h1>
<div class="n-body">
<form action="post" action="">
<select id="nbox" name="newsletters">
<option value="2017">Newsletter 2017</option>
</select>
<button id="nbutton" onclick="displayNewsletter();return false;">Get Newsletter
Link</button>
</form>
<div class="n-row">
<div id="col">xxx</div>
</div>
</div>
<script>
function displayNewsletter() {
var selectedNewsletter = document.getElementById("nbox").value;
var col= document.getElementById("col");
var a = "<h2>2017</h2> <img alt='newsletter' src='http://clone.kmvcss.org/wpcontent/themes/nu2013/images/2017-Newsletter.png' width='60px' height='180px'/> <a href='https://drive.google.com/open?id=0B0vGa180vtK9aDlPZlFIMTRmcDJvZ0l5Ti1WMGxIV3RMV3RV'>xxx</a>";
if (selectedNewsletter == "2017") {
col.innerHTML = a;
}
return false;
}
</script>