简体   繁体   English

在javascript中将变量传递给函数

[英]Passing a variable into a function in javascript

I'm not sure what is wrong with my code. 我不确定我的代码有什么问题。 I keep getting A NaN variable for maxLength. 我一直为maxLength获取一个NaN变量。 Am I writing this function correctly? 我正确地写这个功能了吗?

Helper function I am trying to call: 我试图打电话的助手功能:

(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);

Functions calling to the helper function above: 调用上面的辅助函数的函数:

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

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

Calling to function passing in the maxLength variable 调用函数传递maxLength变量

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

this will refer to the window in your countRemainingCharacters() functions as you don't call it with a scope. this将引用countRemainingCharacters()函数中的window ,因为您不使用范围调用它。 You can fix that using call() : 你可以使用call()修复它:

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

Also note that the logic you use to generate the id of the element to place the message in is a little off. 另请注意,用于生成放置消息的元素的id的逻辑稍微偏离。 You could improve it by using a data attribute to explicitly set the element id. 您可以通过使用data属性显式设置元素ID来改进它。

Your overloaded method is also redundant in this case as you can take advantage of JavaScripts 'falsy' logic to provide a default value if none was provided. 在这种情况下,您的重载方法也是多余的,因为如果没有提供默认值,您可以利用JavaScripts'falsy'逻辑来提供默认值。 This means that you can convert your two countRemainingCharacters() functions in to one: 这意味着您可以将两个countRemainingCharacters()函数转换为一个:

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

Working example 工作实例

All that would be left at that point is to create a key event handler to calculate the remaining characters as the user types. 此时剩下的就是创建一个键事件处理程序来计算用户输入的剩余字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM