javascript 如何根据下拉选择更改跨度的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11444042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change content of a span based on Drop down selection
提问by user1074803
I have a select box and a label with a span, I want to replace span content as users change their selection on the drop down box.
我有一个选择框和一个带跨度的标签,我想在用户更改下拉框中的选择时替换跨度内容。
<select class="text_select" id="field_6" name="field_6">
<option value="- Select -">- Select -</option>
<option value="Option One">Option One</option>
<option value="Option Two">Option Two</option>
<option value="Option Three">Option Three</option>
</select>
<label class="form_field">Your selected <span id="aggregator_name"></span>?</label>
I'm using this script
我正在使用这个脚本
<script type="text/javascript">
function notEmpty(){
var e = document.getElementById("field_6");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('aggregator_name').innerHTML = strUser;
}
notEmpty()
</script>
Problem with this is, whenever I refresh the page, span is replace with "- Select -" but when I change the dropdown to another option, it doesn't change content of the span? Please help guys.
问题是,每当我刷新页面时,跨度都会替换为“-选择-”,但是当我将下拉列表更改为另一个选项时,它不会更改跨度的内容?请帮助伙计们。
回答by nnnnnn
You need to call your function from the change event of the drop-down:
您需要从下拉列表的更改事件中调用您的函数:
document.getElementById("field_6").onchange = notEmpty;
Demo: http://jsfiddle.net/Mj4Vj/
演示:http: //jsfiddle.net/Mj4Vj/
Or, since you've used the "jquery" tag, the following replaces all of your JS:
或者,由于您使用了“jquery”标签,以下内容将替换您的所有 JS:
$(document).ready(function() {
$("#field_6").change(function() {
$('#aggregator_name').html($(this).val());
}).change();
});
Demo: http://jsfiddle.net/Mj4Vj/1/
演示:http: //jsfiddle.net/Mj4Vj/1/
(Note: if the above is included in a script block that appears after the "field_6" element, e.g., if your script is at the end of the body, then you don't need to wrap the code in a document ready handler.)
(注意:如果上述内容包含在出现在“field_6”元素之后的脚本块中,例如,如果您的脚本位于正文的末尾,那么您不需要将代码包装在文档就绪处理程序中。 )
回答by Tats_innit
Working demohttp://jsfiddle.net/GEfwE/1/
工作演示http://jsfiddle.net/GEfwE/1/
Behaviour: when ever you will change anything you will see the cahnge in span,
行为:当你改变任何东西时,你会看到跨度的变化,
Hope this helps, please lemme know if I missed anything! `:)~
希望这会有所帮助,如果我错过了什么,请让我知道!`:)~
code
代码
$('select').change(function(){
$('#aggregator_name').html($(this).val());
});
?
回答by kevin
you can use onchange.
你可以使用onchange。
var e = document.getElementById("field_6");
e.onchange = function() {
var strUser = e.options[e.selectedIndex].value;
document.getElementById('aggregator_name').innerHTML = strUser;
}