我在写反码。我有以下函数,它需要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只会第一次传递。最小值、最大值和其他两个参数的值都是未知的。这个代码有什么问题?
发布于 2015-03-25 12:16:43
将函数添加到回调中,而不是直接在change()中添加
$('#profile_short_description_textarea').change(function() {
updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message');
});发布于 2015-03-25 12:13:01
像这样使用
$('#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');
});发布于 2015-03-25 12:21:18
你需要做以下几件事。
$(function() {
$('#profile_short_description_textarea').on("keyup change", function() {
updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message');
});
});我已经将多个事件合并到一个事件中,因为它是在同一个元素上触发的!
因为下面是错误的!
$('#profile_short_description_textarea').change(updateCountdown(100,150,'#profile_short_description_textarea', '#short_description_message'));当函数没有参数时,可以这样做,例如,
$('#profile_short_description_textarea').change(updateCountdown);其中的函数看起来可能是:
function updateCountdown() {...}https://stackoverflow.com/questions/29255314
复制相似问题