2013-12-23 30 views
0

我试图在搜索框中输入一个值,并将该值用作另一个函数的参数,但每次单击按钮时,当页面刷新时,全局变量会重置自身。在javascript函数中使用搜索框

这是我在我的javascript代码:

var searchTags; 

function DoSearch() 
{ 
    searchTags = $('#squery').val(); 
} 

dataservices.pictureFeedService.searchForPictures(searchTags, function (data) { 
    dataservices.picturesLayoutService.buildPicturesLayout("images", data); 
}); 

和HTML代码在我的索引我的搜索框旁边:

<form id="custom-search-form" class="form-search form-horizontal"> 
     <div class="input-append span2 offset5"> 
      <input id="squery" type="text" class="search-query" placeholder="Search"/> 
      <button type="submit" onclick="DoSearch();" class="btn"><i class="icon-search"></i></button> 
     </div> 
</form> 

我在我的节目3个JS文件:这个js代码在main.js中,另一个js文件中我使用dataservices.pictureFeedService和dataservices.picturesLayoutService,以及最后一个js文件,我只有这个:

dataservices = {}; 
+0

您的输入是实际提交并刷新页面的表单吗?你怎么知道它重置自己。你的dataservices函数如何被调用?为什么不把它称为功能而不是外部。 – Leeish

+0

_页面刷新时,全局变量会自行重置。是的,这通常是JS变量发生的情况。 – putvande

+0

你不需要提交表格。 从'button'中删除'type =“submit”' – AbsarAkram

回答

0
$('#custom-search-form button[type="submit"]').click(function(e){ 
    e.preventDefault(); 
    dataservices.pictureFeedService.searchForPictures($('#squery').val(), function (data) { 
     dataservices.picturesLayoutService.buildPicturesLayout("images", data); 
    }); 
} 
+0

它不适用于我的程序:(请阅读我以前的评论 – Razziel

+0

我根据您的意见编辑了 – Leeish

+0

对不起,您的解决方案很好,但是您没有掌握所有信息,这是我的错,我没有非常了解javascript – Razziel

1

要停止刷新页面,您需要阻止表单提交。

var form; 

    // get your form's id 
    form = $('#yourformid'); 

    form.submit(function(event) { 
     // stop form from submitting 
     event.preventDefault(); 

     var value; 

     // get search term 
     value = $('#squery').val(); 

     // add your code here to do whatever with your input's value 

    }); 
+0

@Razziel,就像我对你的帖子的第一条评论。即使您没有提供任何操作,表单也会默认提交到该页面。 – Leeish

+0

伟大的解决方案,这比我的Onclick功能更好。非常感谢^^ – Razziel

0

为什么不使用javascript的onkeyup事件。您可以逐字符读取文本框的值,然后使用ajax在数据库中搜索相关结果。

function search(){ 
     var d =document.getElementById('display'); 
     var a = document.getElementById('txt').value; 
     if(a){ 

     var x = new XMLHttpRequest(); 

     x.onreadystatechange = function(){ 

      if(x.readyState==4&& x.status==200){ 

       document.getElementById('display').innerHTML = x.responseText; 
       d.style.display = "block"; 
      } 

     } 
     x.open('GET','ajax.php?search='+a,true); 
     x.send(); 

     }else{ 
      d.style.display = "none"; 
     } 
    } 

</script> 
<style> 
    #display{ 
     border: solid medium black; 
     width: 200px; 
     display:none; 

    } 

</style> 


<input type="text" id = 'txt' name="keyevent" onkeyup="search();" value="search" required>Search 

<div id="display"></div>