javascript 选择单选按钮时jQuery更改内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15262025/
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
jQuery change content when radio button selected
提问by Paul Yin
can someone give me help on a simple jQuery code that when clicked different radio bottuon then display the different content.
http://jsfiddle.net/AXsVY/
有人可以帮助我编写一个简单的 jQuery 代码,当单击不同的无线电按钮时,会显示不同的内容。
http://jsfiddle.net/AXsVY/
HTML
HTML
<label class="radio inline">
<input id="up_radio" type="radio" name="optionsRadios" value="update" checked>
Update
</label>
<label class="radio inline">
<input id="ov_radio" type="radio" name="optionsRadios" value="overwritten">
Overwritten
</label>
<p id="cont">
sth. here
</p>
JavaScript
JavaScript
$("#up_radio").click(function(){
if ($("#up_radio").is(":checked")) {
//change to "show update"
$("#cont").value = "show update";
} else if ($("#ov_radio").is(":checked")) {
// change to "show overwritten"
}
});
回答by Popnoodles
Use on change not on click. Click triggers change, but the user could also tab across and hit an arrow key. It will always change
.
使用更改而不是单击。单击会触发更改,但用户也可以使用 Tab 键并点击箭头键。它会一直change
。
$('input[name="optionsRadios"]').on('change', function(){
if ($(this).val()=='update') {
//change to "show update"
$("#cont").text("show update");
} else {
$("#cont").text("show Overwritten");
}
});
Also, the correct syntax to set a value is $("#something").val("the value");
but in this case #cont is a div, so you need to use .text()
or .html()
.
此外,设置值的正确语法是,$("#something").val("the value");
但在这种情况下 #cont 是一个 div,因此您需要使用.text()
or .html()
。
回答by digitalextremist
Solved, based on your approach.. There are more optimizations you could do, but I left it mostly as-is:
解决了,根据你的方法..你可以做更多的优化,但我大部分保持原样:
http://jsfiddle.net/digitalextremist/mqrHs/
http://jsfiddle.net/digitalextremist/mqrHs/
Here's the code outside a fiddle:
这是小提琴外的代码:
$(".radio input[type='radio']").on( 'click', function(){
if ($("#up_radio").is(":checked")) {
$("#cont").html( "show update" );
} else if ($("#ov_radio").is(":checked")) {
$("#cont").html( "show overwritten" );
}
});
回答by PSR
$("input:radio[name=optionsRadios]").click(function() {
var value = $(this).val();
if(value="update")
$("#cont").text("show update");
else
$("#cont").text("show update other");
});