【问题标题】:String Value from jQuery becomes undefined when passed as parameter当作为参数传递时,来自 jQuery 的字符串值变得未定义
【发布时间】:2017-10-27 23:38:30
【问题描述】:

美好的一天,

我正在使用 NodeJS 和 Electron 开发一个宠物项目。目前它基本上是一个简单的文本编辑器。但是,在保存到文件之前尝试将文本区域的值传递给函数时,我遇到了一个问题。 特别是当我在另一个模块中调用函数时,内容的值变为“未定义”。我怀疑我传递它不正确,或者它在我进行调用和调用执行之间被覆盖,因为字符串应该通过引用传递。

Renderer(index.html) 的代码是这样的:

    let otherModule = require('./js/otherModule.js');
    let $ = require('jquery');
    $('#btn_Save').on('click',() => {
        // get the fileName, if empty propmt user with save dialog, 
        //log it to console for debugging
        var contents = $('#txt_Content').val();
        console.log('with:',contents.substring(0,9),'...');
        var finalContents = contents; // (create a copy?)

        if(//someConditionMet//)
        {
            var otherVar = $('#txt_Other').val();
            console.log('Use:',otherVar.substring(0,9),'...');
            finalContents = otherModule.someFunc(contents, otherVar);
        }
        //do something with final contents.
    })// end of On-click

我已经使用 console.log() 来广泛评估该函数,并且可以确认直到调用 otherModule,内容是正确的,并且与 textArea 中的内容相匹配。一旦我们在“otherModule”中,事情出了差错。

otherModule的代码是这样的:

const someFunc = function(contents, otherVar)
{
    console.log('DoThings with:',contents.substring(0,9),'...'); 
    // print shows the value to be undefined...
    // do more things
    console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
    // prints just fine as as expected.
    // do more things
    return someString;
}

module.exports = {
    someFunc: someFunc
}

正如评论中提到的,函数的第一行记录了控制台的内容,控制台将子字符串显示为“未定义”。

感谢您的时间和考虑!

// 额外上下文//

我已经进行了一些搜索,但除了了解字符串是通过引用传递并且是不可变的之外,我还没有看到这样的问题的答案。已经有一些关于闭包问题的讨论,但通常是在事件和回调的上下文中,我认为这不是这里的上下文。

// 额外信息//

我已经找到了让我的参数正确传递的解决方案。我已经在下面发布了答案。我做了两件事: 1.将函数定义从'const'更改为'let' 2. 改变参数的顺序,去掉逗号后面的空格。

【问题讨论】:

    标签: javascript jquery node.js electron


    【解决方案1】:

    如果你得到了 if 里面的值,你应该没问题。

    if(//someConditionMet//)
    {
        var contents = $('#txt_Content').val(); //New line
        var otherVar = $('#txt_Other').val();
        console.log('Use:',otherVar.substring(0,9),'...');
        finalContents = otherModule.someFunc(contents, otherVar);
    }
    

    【讨论】:

    • 感谢您的推荐。但是,当我尝试这没有效果时。我可以验证我是否在“var 内容”中获得了价值,但是当传递给 someFunc 时,我继续收到未定义的数据。
    【解决方案2】:

    我已经找到了解决这个问题的方法。我不确定为什么会有所不同,但我在“otherModule”中更改了两件事。 1.我将函数从'const'更改为'let' 2.我改变了参数的顺序,去掉了逗号后面的空格 新的函数头看起来像:

    let someFunc = function(otherVar,contents) {...}
    

    我还更新了调用以匹配新订单(给定):

    finalContents = otherModule.someFunc(otherVar,contents);
    

    我希望这对将来的某人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2021-12-31
      • 2019-01-07
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多