0

我尝试对许多输入字段进行 jQuery 实时搜索。
只有 1 个输入字段(没有数组),它工作得很好,
但是有许多带有数组的搜索字段,什么都没有发生。
livesearch.php文件现在只说“echo 'test';”)

我希望你能帮助我。

感谢您的回答。
但它仍然不起作用。
我只是不明白为什么 ajax 部分不起作用。
我将代码编辑为以下内容:

    <html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
  <body>
      <div id="main">

        First search field:<br>
        <input type="text" name="search[]" class="search" autocomplete="off">
        <div></div>

        Second search field:<br>
        <input type="text" name="search[]" class="search" autocomplete="off">
        <div></div>

      </div>

      <script>


        $(document).ready(function() {  

          $('.search').on("keyup", function(e) {

            var search_string = $(this).val();

            // Do Search
            if (search_string == '') {
              $(this).next().fadeOut();
            }else{
              $(this).next().fadeIn();

              //$(this).next().html("hallo"); //THIS WORKS!!!


              $.ajax({
                type: "POST",
                url: "./livesearch.php",
                data: { query: search_string },
                cache: false,
                success: function(data){
                  $(this).next().html(data); //THIS DOESN'T WORK!!!
                }
              });

            };
          });

        });

      </script>

  </body>
</html>
4

2 回答 2

0

你的问题的原因很简单,发生这种情况是因为,这个指针this没有显示到与开始时相同的元素。

起初this指向输入元素,这就是它工作正常的原因, 但在 $.ajax request 内部,它意味着**函数 本身成功。**

为了正确工作,将其分配一个新变量并在成功函数中使用变量。

var myInputElmnt = $(this);//assign this to temp variable
.....
$(myInputElmnt).next().html(data); //it works because it shows to your input element

查看我的修复:

$(document).ready(function() {  

          $('.search').on("keyup", function(e) {

            var search_string = $(this).val();

            var myInputElmnt = $(this);//assign this to temp variable

            // Do Search
            if (search_string == '') {
              $(this).next().fadeOut();
            }else{
              $(this).next().fadeIn();

              $(myInputElmnt).next().html("hallo"); //THIS WORKS ALSO


              $.ajax({
                type: "POST",
                url: "./livesearch.php",
                data: { query: search_string },
                cache: false,
                success: function(data){

                  $(myInputElmnt).next().html(data); //it works because it shows to your input element
                }
              });

            };
          });

        });

这应该是诀窍,希望有助于好运。

于 2015-11-29T11:55:53.963 回答
0

我推荐这篇文章使用相同名称的输入。您不能使用 ID 两次。他们应该是独一无二的!

尝试以下操作:

<input type="text" name="search[]" class="search" id="search1" autocomplete="off">
<input type="text" name="search[]" class="search" id="search2" autocomplete="off">

并使用简单的选择器进行简单的阅读 js:

$('.search').on('keyup', ...

ul 似乎总是在.search之后,因此您可以在当前 .search 范围内使用

$(this).next() // jQuery object of ul
于 2015-11-27T00:20:17.017 回答