Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中将变量传递给函数_Javascript_Jquery - Fatal编程技术网

在javascript中将变量传递给函数

在javascript中将变量传递给函数,javascript,jquery,Javascript,Jquery,我不确定我的代码出了什么问题。我一直在为maxLength获取一个NaN变量。我写的这个函数正确吗 我正在尝试调用的助手函数: (function($) { $.fn.countRemainingCharactersHelper = function(maxLength) { id = this.attr('id'); var textLength = this.val().length; var textRemaining = maxLe

我不确定我的代码出了什么问题。我一直在为maxLength获取一个NaN变量。我写的这个函数正确吗

我正在尝试调用的助手函数:

(function($) {
    $.fn.countRemainingCharactersHelper = function(maxLength) {
        id = this.attr('id');
        var textLength = this.val().length;
        var textRemaining = maxLength - textLength;

        if (textLength >= maxLength) {
            textRemaining = 0;
        }

        var messageId = id.slice(0, (id.indexOf('someTxtBox'))) + 'someTxtBox';
        $('#' + messageId).html(textRemaining + ' characters remaining.');
    };
})(jQuery);
调用上述辅助函数的函数:

function countRemainingCharacters() {
    $(this).countRemainingCharactersHelper(1000);
}

function countRemainingCharacters(maxLength) {
    $(this).countRemainingCharactersHelper(maxLength);
}
调用传递maxLength变量的函数

$('#samplesomeTxtBox').click(function() {
    countRemainingCharacters(4000);
});

将引用
countRemainingCharacters()
函数中的
窗口
,因为您不使用作用域调用它。您可以使用
call()
修复此问题:

还要注意,用于生成放置消息的元素的
id
的逻辑有点不正确。您可以通过使用
data
属性显式设置元素id来改进它

在这种情况下,重载方法也是多余的,因为如果没有提供默认值,您可以利用JavaScripts“falsy”逻辑来提供默认值。这意味着您可以将两个
countRemainingCharacters()
函数转换为一个:

function countRemainingCharacters(maxLength) {
    $(this).countRemainingCharactersHelper(maxLength || 1000);
}


此时剩下的就是创建一个关键事件处理程序来计算用户键入的剩余字符。

非常感谢Rory!!我肯定不知道这个错误的逻辑。
function countRemainingCharacters(maxLength) {
    $(this).countRemainingCharactersHelper(maxLength || 1000);
}