2016-09-10 4 views
0

문제가 생겼습니다. 요소를 사용하여 .search_box 요소를 CLOSEST로 선택하려고 시도했으며, PHP의 jQuery 및 show 목록을 사용했습니다.클래스를 선택하는 방법

$(".results").show().append(html) 

PHP의 목록에 거의 모든 요소가 표시되었으므로 작동하지 않습니다. 나는 약간의 다이나믹을 추가하는 .calc_input_wrapper을 가지고있다.

$(this).closest(".results").show().append(html) 

이것은 작동하지 않습니다.

<div class="calc_input_wrapper clearfix"> 
    <ul class="calc_input_list clearfix"> 
    <li class="product_number">1</li> 
    <li class="product_input"> 
     <form method="post" action="do_search.php"> 
     <input autocomplete="off" placeholder="Продукт" type="text" name="search" class='search_box'/> 
     </form> 
     <div class="delete_product_row"></div> 
     <ul class="results" class="update"> 
     </ul> 
    </li> 
    <li class="product_weight"> 
     <form action=""> 
     <input autocomplete="off" type="text" placeholder="0"> 
     </form> 
    </li> 
    <li class="product_protein">-</li> 
    <li class="product_fat">-</li> 
    <li class="product_carboh">-</li> 
    <li class="product_calor">-</li> 
    </ul> 
</div> 

$(document).on('keyup', '.search_box', function() { 
    // получаем то, что написал пользователь 
    var searchString = $(this).val(); 
    // формируем строку запроса 
    var data = 'search=' + searchString; 
    // если searchString не пустая 
    if(searchString.length > 1) { 
    // делаем ajax запрос 
    $.ajax({ 
     type: "POST", 
     url: "do_search.php", 
     data: data, 
     beforeSend: function(html) { 
     $(".results").html(''); 
     $("#searchresults").show(); 
     $(".word").html(searchString); 
     }, 
     success: function(html){ 
     //$(".results").show().append(html);       
     console.log('omg'); 
     } 
    }); 
    } else { 
    $(".results").html(''); 
    } 
    return false; 
}); 
+1

'=)'이 (가) 어떻게됩니까? –

답변

0

$(this)은 아약스 메소드 '콜백 내부에서 동일하지 않습니다. $.ajax 메서드를 호출하는 코드 앞에 this은 사용자가 입력 한 입력 상자를 나타냅니다. 하지만 아약스 메소드의 성공 콜백 this은 xhr 객체를 나타냅니다. 그래서 나는 당신이 ajax 호출 외부의 변수에 $(this)을 유지하고 사용하는 것이 좋습니다.

또한 메서드를 사용하여 CSS22 클래스 "product_input"을 사용하여 li 요소를 얻고 find() 메서드를 사용하여 결과 div를 가져와야합니다.

var _this = $(this); 
$.ajax({ 
      //Your existing code 
      success: function(html){ 
       _this.closest(".product_input").find(".results").show().html(html);  

      } 
     }); 

또 다른 옵션은 아약스 호출을 할 때 context 속성을 사용하는 것입니다. 이렇게하면 this은 그대로 유지됩니다. 따라서 로컬 변수 대신 $(this)을 간단히 사용할 수 있습니다.

$.ajax({ 
     //your existing code 
     context: this, 
     success: function (html) { 
      $(this).closest(".product_input").find(".results").show().html(html); 
     } 
    }); 
관련 문제