我有一个下拉字段,当更改时应显示一个按钮,可以根据下拉选项下载文件。问题是它保持附加按钮,所以如果选择1,它会显示1个按钮,在选择另一个选项时,它会附加另一个按钮,依此类推。因此,对于每个选择,按钮不断加起来而不是只显示一个按钮。我尝试添加$('#buttondownload')。remove(),但它无法正常工作。这是代码:
function showFields(this) {
if (this.value == "1" || this.value == "2")
{
download.style.display = "block";
}
if (this.value == "")
{
download.style.display = "none";
}
if (this.value == "1")
{
var file = "'test.pdf";
}
if (this.value == "2")
{
var file = "test2.pdf";
}
html = '<button type="button" onClick="location.href='+ file + '">Download File</button>'
$('#buttonDownload').append(html);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" name="ID" onChange="showFields(this);">
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="download"><div id="buttonDownload"></div></div>
&#13;
答案 0 :(得分:2)
您需要在添加新按钮之前清除容器:
$('#buttonDownload').empty().append(html);
答案 1 :(得分:1)
你是append
按钮。改为替换旧按钮:
function showFields() {
// ...
html = '<button type="button" onClick="location.href=XXX">Download File</button>'
$('#buttonDownload').html(html);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" name="ID" onChange="showFields(this);">
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="download">
<div id="buttonDownload"></div>
</div>
&#13;