2014-07-01 82 views
-3

我的網站上有一個搜索框。它工作正常,但突然停止工作,當我添加我的網站視頻頁面。我不斷收到一個錯誤說「未捕獲的ReferenceError:搜索沒有定義」,似乎我無法找到是什麼錯誤爲什麼搜索沒有定義?

的header.php

<center> 
    <input type="text" id="searchbar" onkeydown="search()" style="width:60%;font-size:17px;font-weight:bold; height:40px; padding:0px 10px; margin:3px 0px 0px 0px; border-radius:15px;" placeholder="Search for People, Videos, #hashtags and Blogs..." value="<?php echo $search; ?>"/> 
</center> 

我的頁腳頁面:footer.php

function search(){ 
    var keycode = (event.keyCode ? event.keyCode : event.which); 
    if(keycode == '13'){ 
     var str = post = document.getElementById("searchbar").value; 
     if(str.indexOf("#") == 0){ 
      var result = str.replace('#', ''); 
      var result = result.replace(/ /g, '%20'); 
      window.location.assign("http://www.daparadise.com/testing/daparadise2/search.php?type=hashtag&search=" + result); 
     }else if(str.indexOf("people named") == 0){ 
      var result = str.replace('people named ', ''); 
      var result = result.replace(/ /g, '%20'); 
      window.location.assign("http://www.daparadise.com/testing/daparadise2/search.php?type=people&search=" + result); 
     }else if(str.indexOf("videos") == 0){ 
      var result = str.replace('videos ', ''); 
      var result = result.replace(/ /g, '%20'); 
      window.location.assign("http://www.daparadise.com/testing/daparadise2/search.php?type=videos&search=" + result); 
     }else if(str.indexOf("blogs") == 0){ 
      var result = str.replace('blogs ', ''); 
      var result = result.replace(/ /g, '%20'); 
      window.location.assign("http://www.daparadise.com/testing/daparadise2/search.php?type=blogs&search=" + result); 
     }else{ 
      var result = result.replace(/ /g, '%20'); 
      window.location.assign("http://www.daparadise.com/testing/daparadise2/search.php?type=web&search=" + result); 
     } 
    } 
} 
+1

關於你的編碼風格的一些事情 - 在函數的頂部聲明你的變量只有一次;使用===與0比較;不要聲明你永遠不會使用的變量(在這種情況下變量post);正確使用正則表達式/ \ s /而不是/ /,如果一切都失敗,最後會有一個默認情況,就像你的情況一樣。 – hex494D49

回答

1

這通常表示在您的代碼中(在函數中或在它之前)存在某種形式的語法錯誤,這會阻止Javascript解釋器達不到函數的定義。這是「未定義」。

檢查您的瀏覽器日誌中的Javascript錯誤,它應該指向罪魁禍首(這很可能不在上面的代碼中)。

+0

非常感謝!我查看了開發人員區域,發現我的javascript在我的搜索功能中有錯誤。它現在工作正常! :) – Zacharysr

0

如果我是你的代碼複製到一個崇高的文本文檔,保存並在Chrome中打開HTML ...瀏覽器引用的最後else條款的聲明和報告的行號:

Uncaught TypeError: Cannot read property 'replace' of undefined 

對應於此分配:

else { 
    var result = result.replace(/ /g, '%20'); 
    /* etc. */ 

如果您的所有if條件達不到,這是默認的動作......這不能引用自身在其自己的初始值的定義,它尚未確定。

申報var result進入的if/else語句序列,並事先給它一個默認值,太(最好是字符串,因爲你使用String.replace,當然)前。它可以是這樣簡單的:

if(keycode === '13') { 
    var result = ''; 
    var str = /* etc, etc. */ 
+0

這不是問題。 – Popnoodles