2012-05-09 19 views
0

該程序應該是一個使用PHP和JavaScript的實時搜索...當你鍵入它搜索下面。我只是最近纔開始學習JavaScript很抱歉,如果我的知識是有限的......引用變量,它執行該函數,但是將字符串添加到變量,返回函數作爲字符串,而不是值

$(document).ready(function() { 
    $('#results').append('<p>Started</p>'); 
    var getText = (function() { 
     return document.getElementById('year').value; 
    }); 
    var text = getText; 
    var getText1 = (function() { 
     return document.getElementById('class').value; 
    }); 
    var text1 = getText1; 
    setInterval(function() { 
     var newText = getText; 
     var newText1 = getText1; 
     var loading = "search.php?year=" + newText + "&class=" + newText1; 
     $('#results').append(newText1); 
     if (text !== newText || text1 !== newText1) { 
      $('#results').load(loading); 
      $('#results').append('somethinghappened'); 
     }; 
     text = newText; 
     text1 = newText1; 
    }, 100); 
}); 

所以它工作正常,當我追加newText1,但是如果我嘗試添加「加載」返回:

search.php?year = function(){return document.getElementById(「year」)。value; } & class = function(){return document.getElementById(「class」)。value; }

任何人都可以解釋兩種情況之間的區別是什麼以及爲什麼會出現差異?並可能如何解決它,以便它加載正確的URL

我搜索並找到:JavaScript: When assigning an anonymous function to a variable, function return value is not passed, rather the function as a string但是完全不完全理解這是什麼意思傳遞兩個參數,當我試圖做類似的事情時,噸工作如預期...

任何幫助表示讚賞,並提前感謝。

+5

這是一個標題,而不是一個故事... **:)** – gdoron

回答

0
var newText = getText; 
var newText1 = getText1; 

您分配功能getTextgetText1的變量,而不是執行它們並指派其返回值。試試這個:

var newText = getText(); 
var newText1 = getText1(); 

或者只是:

var newText = document.getElementById('year').value; 
var newText1 = document.getElementById('class').value; 
0

試圖簡單地用

var getText = document.getElementById('year').value; 
var getText1 = document.getElementById('class').value; 

,否則,你將有隻有參考作用

0

你不調用功能,你只是引用它們。

給他們打電話你需要parens,像getText()。但爲什麼在這種情況下使它們起作用?它們很短,不需要參數。如果你想要的功能,使一個單一的功能,採用字符串的ID。

相關問題