2013-12-20 1 views
0

새 필드 줄을 추가하는 버튼이있는 WordPress 위젯에서 작업하고 있습니다. 어떤 이유로이 코드가 100 % 작동하지 않습니다. 페이지를 새로 고친 다음 버튼을 누르면 처음 두 필드가 추가되고 두 ​​번째 필드가 추가됩니다. 그러나 먼저 저장 버튼을 클릭하면 완벽하게 작동합니다. 어떤 아이디어?WordPress 위젯 - JQuery 필드 추가 버튼 - 두 번 발동

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" />'; 
} 

답변

2

이것은 js가 설정을 관리해야하는 위젯에서 자주 발생하는 문제입니다. 우리 회사는 많은 사용자 정의 위젯을 사용하며, 나는이 동일한 문제를 여러 번 경험했습니다. 문제는 자바 스크립트에서 발생하며 전체 페이지와 상호 작용합니다. 페이지에 위젯이 2 개있는 경우 즉시 문제가 발생합니다. 참고로이 위젯을 사이드 바에 추가하면 이미 위젯 중 두 개, 즉 사이드 바에 추가 한 위젯과 위젯의 '풀'내부에 위젯 중 두 개가 이미 있습니다. 설명하겠습니다.

기본 사이드 바에 위젯을 추가하자. 저장을 클릭하고 페이지를 다시로드하십시오. 이제 기본 사이드 바 아래에이 위젯이 있으며 추가 버튼을 클릭하면 두 번 실행됩니다. 왜? 그 이유는 자바 스크립트가 페이지의 ALL $('.addfeature')에 첨부되어 있고이 위젯이 페이지의 모든 사본에 대해 한 번 실행되기 때문입니다. 당신은 사이드 바에 하나의 사본이 있고, WordPress가 새로운 위젯을 복제 할 때 사용하는 사본 하나가 위젯 풀에 있습니다.

일반적으로 말해 가장 쉬운 해결책은 .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" />'; 

우리 회사는 여러 번이 문제를 여러 번 극복했습니다. $this->get_field_id 함수는 WP_Widget을 확장하는 모든 클래스에서 사용할 수 있습니다. 위젯 관리 페이지가 여러 사이드 바 및 위젯 풀에서 위젯을 고유하게 식별하는 데 사용하는 고유 한 ID (및 자리 표시 자 고유 ID)를 생성합니다. 이 유형의 솔루션은 위젯 관리 페이지의 거의 모든 자바 스크립트 문제를 해결합니다. 희망이 당신과 비슷한 문제가 다른 사람을 도와줍니다.

+0

끔찍한 답변! 설명해 주셔서 감사합니다. 위젯 풀에 대해서는 전혀 몰랐습니다. – Tenatious

+0

예. 나는 이것을 처음으로 많은 시간을 보냈다. 다시는 절대 권해라. – loushou

관련 문제