【问题标题】:How to select a class如何选择班级
【发布时间】:2017-01-18 14:48:00
【问题描述】:

我有一个问题,我尝试使用 jQuery 选择 CLOSEST to .search_box.results 的元素并显示来自 PHP 的列表。

$(".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;
});

【问题讨论】:

  • =) 怎么了?

标签: jquery html ajax jquery-selectors


【解决方案1】:

$(this) 在 ajax 方法的回调中不会相同。在调用$.ajax 方法的代码之前,this 代表用户输入某个值的输入框。但是在ajax方法的成功回调里面this代表的是xhr对象。因此,我建议您将 $(this) 保留在您的 ajax 调用之外的变量中并使用它。

您还应该使用closest() 方法获取具有css 类“product_input”的外部li 元素,并使用find() 方法获取结果div。

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

          }
      });

另一个选项是在进行 ajax 调用时使用context 属性。这将使您的this 保持原样。所以你可以简单地使用$(this) 而不是局部变量。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2023-03-30
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多