我正在写一个计数器代码。我有以下需要 4 个参数的函数。 'fieldSelector' 是文本区域的 id 或类选择器,'msgSelector' 是必须显示文本消息的范围。 'min' 和 'max' 是文本的最小和最大限制。
function updateCountdown(min, max, fieldSelector, msgSelector) {
alert(msgSelector)
var chars = jQuery(fieldSelector).val().length;
var remaining = max - chars;
if (chars < min){
var moreChars = min - chars;
jQuery(msgSelector).addClass('text-danger');
if (chars == 0)
jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' characters.');
else if (chars == min-1)
jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' more character.');
else
jQuery(msgSelector).text('You need to add atleast ' + moreChars + ' more characters.');
}
else
{
jQuery(msgSelector).removeClass('text-danger');
if (remaining <=10)
jQuery(msgSelector).addClass('text-danger');
if (remaining == 1)
jQuery(msgSelector).text('You can add only ' + remaining + ' more character.');
else if (remaining > 0)
jQuery(msgSelector).text('You can add ' + remaining + ' more characters.');
else if (remaining == 0)
jQuery(msgSelector).text('Your limit has been ended.');
else if (remaining == -1)
jQuery(msgSelector).text('You have exceded ' + (-remaining) + ' character.');
else
jQuery(msgSelector).text('You have exceded ' + (-remaining) + ' characters.');
}
}
我用以下方式调用这部分。
$(document).ready(function(){
$('#profile_short_description_textarea').change(updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message'));
$('#profile_short_description_textarea').keyup(updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message'));
});
参数值 min、max、fieldSelector 和 msgSelector 仅在文档加载时第一次传递。 min、max 和其他两个参数的值未定义。这段代码有什么问题?
最佳答案
像这样使用
$('#profile_short_description_textarea').change(function() {
updateCountdown(100, 150, '#profile_short_description_textarea', '#short_description_message');
});
$('#profile_short_description_textarea').keyup(function() {
updateCountdown(100, 150, '#profile_short_description_textarea', '#short_description_message');
});
关于javascript - JS和Jquery函数参数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255314/