我想创建一个动态链接,其值从html中选择。以下是我可以做的示例代码。
<select name="sequence" id="sequence" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option>file1</option>
<option>file2</option>
<option>file3</option>
</select>
<a href="data/file1"><span id="selectedValue"></span></a>
如何使用所选选项动态创建此链接。
答案 0 :(得分:3)
function changeLink(val){
document.getElementById('selectedValue').innerHTML = val;
document.getElementById('link').href="data/"+val;
}
<select name="sequence" id="sequence" onChange="changeLink(this.value);">
<option>file1</option>
<option>file2</option>
<option>file3</option>
</select>
<a id="link" href="data/file1"><span id="selectedValue"></span></a>
答案 1 :(得分:0)
onChange="document.getElementById('selectedValue').innerHTML = 'data/' + this.options[this.selectedIndex].text;"
答案 2 :(得分:0)
<select name="sequence" id="sequence" onChange="document.getElementById('selectedValue').innerHTML = this.value;
document.getElementById('myLink').href = 'data/' + this.value;">
<option>file1</option>
<option>file2</option>
<option>file3</option>
</select>
<a id="myLink" href="data/file1"><span id="selectedValue"></span></a>
请参阅fiddle。
答案 3 :(得分:0)
演示:JSFiddle。
<script>
function change(e) {
console.log(e.value);
document.getElementById('selectedValue').innerHTML = e.value;
}
</script>
<a href="data/file1"><span id="selectedValue"></span></a>
<select id="c1" onchange="change(this)">
<option value="value-1">One</option>
<option value="value-2">Two</option>
<option value="value-3">Three</option>
</select>
答案 4 :(得分:0)
嗨,我真的想到了代码的分离,所以我只是给你一个解决你的问题的解决方案在JSFiddle
https://jsfiddle.net/zjyLqLLx/
这是您的HTML,我只是更改了&#34; span&#34;元素到&#34; a&#34;元素,以便更改网址
<select name="sequence" id="sequence">
<option>Default Text</option>
<option>file1</option>
<option>file2</option>
<option>file3</option>
</select>
<a id="selectedValue" href="Hola">
<span>Some Default Value</span>
</a>
和你的javascript代码
document.getElementById('sequence').addEventListener('change', function(){
var selected = this.options[this.selectedIndex].text;
var link = document.getElementById('selectedValue');
link.innerHTML = selected;
link.href = "data/" + selected;
});
它已经在使用JSFiddle
了