引用变量,它执行函数,但是向变量中添加字符串,将函数作为字符串而不是值返回

Referencing variable,it executes the function,however adding strings to the variable,returns function as string instead of value

本文关键字:字符串 函数 变量 返回 执行 引用 添加      更新时间:2023-09-26

该程序应该是使用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:将匿名函数分配给变量时,不会传递函数返回值,而是将函数作为字符串,但是不太完全理解传递两个参数的含义,当我尝试做类似的事情时,它没有按预期工作......

任何帮助,非常感谢,提前感谢。

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;

试试

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

否则,您将只有对该函数的引用

你不是在调用函数,你只是在引用它们。

要称呼它们,您需要像 getText() 一样的 parens.但是,在这种情况下,为什么要使它们起作用呢?它们很短,不带参数。如果需要函数,请创建一个采用字符串 ID 的函数。