WordPress小部件-JQuery添加字段按钮-激发两次

WordPress小部件-JQuery添加字段按钮-激发两次,jquery,wordpress,foreach,widget,Jquery,Wordpress,Foreach,Widget,我正在开发一个WordPress小部件,它有一个按钮,按下按钮时会添加一个新的字段行。由于某些原因,此代码无法100%工作。如果我刷新页面,然后按下按钮,第一次会添加两个字段,第二次会添加3个字段。但是,如果我先单击“保存”按钮,它就可以正常工作。有什么想法吗 public function form( $instance ) { $title = isset ( $instance['title'] ) ? $instance['title'] : ''; $title =

我正在开发一个WordPress小部件,它有一个按钮,按下按钮时会添加一个新的字段行。由于某些原因,此代码无法100%工作。如果我刷新页面,然后按下按钮,第一次会添加两个字段,第二次会添加3个字段。但是,如果我先单击“保存”按钮,它就可以正常工作。有什么想法吗

 public function form( $instance )
{
    $title = isset ( $instance['title'] ) ? $instance['title'] : '';
    $title = esc_attr( $title );

    printf(
        '<p><label for="%1$s">%2$s</label><br />
        <input type="text" name="%3$s" id="%1$s" value="%4$s" class="widefat"></p>',
        $this->get_field_id( 'title' ),
        'Title',
        $this->get_field_name( 'title' ),
        $title
    );

    $fields = isset ( $instance['fields'] ) ? $instance['fields'] : array();
    $field_num = count( $fields );
    $fields[ $field_num ] = '';
    $fields_html = array();
    $fields_counter = 0;
    print_r($field_num);
    foreach ( $fields as $name => $value )
    {
        $fields_html[] = sprintf(
            '<input type="text" name="%1$s[%2$s]" value="%3$s" class="widefat feature%2$s">',
            $this->get_field_name( 'fields' ),
            $fields_counter,
            esc_attr( $value )
        );
        $fields_counter += 1;
        if ($fields_counter == $field_num) break;
    }


    print 'Fields<br />' . join( '<br />', $fields_html );
    ?>
    <script type="text/javascript">
        var fieldname = <?php echo json_encode($this->get_field_name( 'fields' )) ?>;
        var fieldnum = <?php echo json_encode($fields_counter - 1) ?>;

        jQuery(function($) {
            var count = fieldnum;
            $('.addfeature').click(function() {
                $( ".feature"+count).after("<input type='text' name='"+fieldname+"["+(count+1) +"]' value='' class='widefat feature"+ (count+1) +"'>" );
                count++;

            });
        });
    </script>
    <?php
    echo '<input class="button addfeature" type="button" value="' . __( 'Add Feature', 'myvps' ) . '" id="addfeature" />';
}
公共函数表单($instance)
{
$title=isset($instance['title'])?$instance['title']:'';
$title=esc_attr($title);
printf(
“%2$s

', $this->get_field_id('title'), “头衔”, $this->get_field_name('title'), $title ); $fields=isset($instance['fields'])?$instance['fields']:数组(); $field_num=计数($fields); $fields[$field_num]=''; $fields_html=array(); $fields\u计数器=0; 打印($field\u num); foreach($name=>$value的字段) { $fields\u html[]=sprintf( '', $this->get_field_name('fields'), $fields\u计数器, esc_属性($value) ); $fields\u counter+=1; 如果($fields\u counter==$field\u num)中断; } 打印“Fields
”。join(“
”,$Fields\u html); ?> 变量fieldname=; var fieldnum=; jQuery(函数($){ var count=fieldnum; $('.addfeature')。单击(函数(){ $(“.feature”+计数)。在(“”)之后; 计数++; }); });
这是需要js来管理其设置的小部件的常见问题。我的公司有很多自定义小部件,我也有过很多次同样的问题。问题在于javascript及其与整个页面的交互。如果页面上有两个If这些小部件,您会立即遇到问题。仅供参考,如果您添加此widge对于任何侧栏,页面上已经有两个小部件,一个刚刚添加到侧栏,另一个在小部件的“池”中。让我解释一下

假设您将该小部件添加到主边栏。您单击“保存”并重新加载页面。现在您的主边栏下有了该小部件,您单击“添加”按钮,它会触发两次。为什么?原因是您的javascript附加到了所有
$('.addfeature'))
,并且它对页面上此小部件的每个副本运行一次。您在侧栏中有一个副本,在小部件池中有一个副本,WordPress使用它克隆新小部件

一般来说,最简单的解决方案是将javascript目标设置为特定的
.addfeature
,而不是所有的
.addfeature
。如何实现?如下所示:

// your code
...
print 'Fields<br />' . join( '<br />', $fields_html );
?>
<script type="text/javascript">
    var fieldname = <?php echo json_encode($this->get_field_name( 'fields' )) ?>;
    var fieldnum = <?php echo json_encode($fields_counter - 1) ?>;

    jQuery(function($) {
        var count = fieldnum;
        // change this from simply '.addfeature' to a unique version of the name
        // which wordpress widget page will interpret for you, making it a unique
        // value for each copy of the widget, including the one in the widget pool
        $('.<?php echo $this->get_field_id('addfeature') ?>').click(function() {
            $( ".feature"+count).after("<input type='text' name='"+fieldname+"["+(count+1) +"]' value='' class='widefat feature"+ (count+1) +"'>" );
            count++;

        });
    });
</script>
<?php
// change this from simply 'addfeature' to a unique version of the name
// which wordpress widget page will interpret for you, making it a unique
// value for each copy of the widget, including the one in the widget pool
echo '<input class="button '.$this->get_field_id('addfeature').'" type="button" value="' . __( 'Add Feature', 'myvps' ) . '" id="addfeature" />';
//您的代码
...
打印“Fields
”。join(“
”,$Fields\u html); ?> 变量fieldname=; var fieldnum=; jQuery(函数($){ var count=fieldnum; //将其从简单的“.addfeature”更改为名称的唯一版本 //哪个wordpress小部件页面将为您解释,使其成为一个独特的页面 //小部件的每个副本的值,包括小部件池中的副本 $('..)。单击(函数(){ $(“.feature”+计数)。在(“”)之后; 计数++; }); });
真棒的回答!谢谢你的解释。我不知道小部件池。是的。我第一次花了很多时间研究这个。再也没有了哈哈