从页面加载的输入中获取值

时间:2015-03-03 22:28:07

标签: jquery

我想在span类活动颜色中显示已选中单选按钮的值。它有效,但不适用于页面加载。我必须检查第二个单选按钮以显示效果。我找到了解决方案,但我认为这不是最好的。

<span class="active-color"></span>

<div class="swatch-element">        
<input id="schwarz" type="radio" name="color" value="Schwarz" checked="checked">        
</div>

<div class="swatch-element">        
<input id="weiss" type="radio" name="color" value="weiss">        
</div>



$(".swatch-element input:radio").change(function(){
$('.active-color').text($(".swatch-element input:checked").val());
})  

我的解决方案

$(".swatch-element input:radio").change(function(){
$('.active-color').text($(".swatch-element input:checked").val());
})  
$('.active-color').text($(".swatch-element input:checked").val());

2 个答案:

答案 0 :(得分:0)

鉴于您已定义了change事件处理程序,最简单的方法是通过调用不带参数的change方法来触发change()事件:

// the anonymous function binds the change event-handler:
$(".swatch-element input:radio").change(function(){
    $('.active-color').text($(".swatch-element input:checked").val());
// triggers the change event (which is then handled by the handler):
}).change();

值得注意的是change事件仅在检查无线电输入时触发,因此在匿名函数中您只需使用this

// the anonymous function binds the change event-handler:
$(".swatch-element input:radio").change(function(){
    $('.active-color').text(this.value);
// triggers the change event (which is then handled by the handler):
}).change();

参考文献:

答案 1 :(得分:0)

将您的代码放入文档中:

$(document).ready(
$(".swatch-element input:radio").change(function(){
$('.active-color').text($(".swatch-element input:checked").val());
})