你有这个问题是因为radio
按钮具有不同的name
; i、 e。the_style_1
和the_style_2
.
所以我建议你使用the_style
作为name
对于radio
按钮:
<p> <input class="radio" type="radio" <?php checked( $instance[ \'the_style\' ], \'style_1\' ); ?> id="<?php echo $this->get_field_id( \'the_style_1\' ); ?>" name="<?php echo $this->get_field_name( \'the_style\' ); ?>" value="style_1" />
<label for="<?php echo $this->get_field_id( \'the_style_1\' ); ?>">This will display the snippet style 1</label>
</p>
<p> <input class="radio" type="radio" <?php checked( $instance[ \'the_style\' ], \'style_2\' ); ?> id="<?php echo $this->get_field_id( \'the_style_2\' ); ?>" name="<?php echo $this->get_field_name( \'the_style\' ); ?>" value="style_2" />
<label for="<?php echo $this->get_field_id( \'the_style_2\' ); ?>">This will display the snippet style 2</label>
</p>
在小部件“display”回调中
function
, 您可以这样做:
public function widget( $args, $instance ) {
// ... other code here.
// Here, style_1 would be the default style, unless you change it below.
$the_style = isset( $instance[\'the_style\'] ) ? $instance[\'the_style\'] : \'style_1\';
if ( \'style_1\' === $the_style ) {
// Do something if the_style is style_1
} elseif ( \'style_2\' === $the_style ) {
// Do something if the_style is style_2
}
// ... other code here.
}
(您还需要更新
update()
小部件的功能
class
.)
或者,如果您只想/需要使用相同的name
对于radio
按钮,然后需要使用JavaScript/jQuery将选择限制为radio
按钮。请参见下面的jQuery脚本示例,您可以尝试:
<script>
jQuery( function( $ ){
// If the_style_1 is checked, uncheck the_style_2.
$( \'#<?php echo $this->get_field_id( \'the_style_1\' ); ?>\' ).on( \'change\', function(){
$( \'#<?php echo $this->get_field_id( \'the_style_2\' ); ?>\' ).prop( \'checked\', ! this.checked );
} );
// If the_style_2 is checked, uncheck the_style_1.
$( \'#<?php echo $this->get_field_id( \'the_style_2\' ); ?>\' ).on( \'change\', function(){
$( \'#<?php echo $this->get_field_id( \'the_style_1\' ); ?>\' ).prop( \'checked\', ! this.checked );
} );
} );
</script>
您可以将该脚本添加到小部件选项表单中(即
form()
小部件的功能
class
), 但请确保jQuery已经加载。
希望有帮助!