微件后端单选按钮问题

时间:2018-04-28 作者:The WP Intermediate

我在我的小部件中使用这种安排。php→

<p> <input class="radio" type="radio" <?php checked( $instance[ \'the_style_1\' ], \'on\' ); ?> id="<?php echo $this->get_field_id( \'the_style_1\' ); ?>" name="<?php echo $this->get_field_name( \'the_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_2\' ], \'on\' ); ?> id="<?php echo $this->get_field_id( \'the_style_2\' ); ?>" name="<?php echo $this->get_field_name( \'the_style_2\' ); ?>" />
<label for="<?php echo $this->get_field_id( \'the_style_2\' ); ?>">This will display the snippet style 2</label>
</p>
但在后端,单选按钮的工作方式不正确(一次只能选择一个)

enter image description here

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

你有这个问题是因为radio 按钮具有不同的name; i、 e。the_style_1the_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已经加载。

希望有帮助!

结束