我正在开发一个基本的积分计数器小部件。我之前有一个问题得到了解答,以帮助我继续前进。但我还有最后一个问题。基本上,我有一个将返回 true 或 false 的函数,但我需要第三个选项。
逻辑是:
- 如果输入字符数在范围内,用户将获得积分
- 如果用户编辑并且计数保持在范围内,则没有新点
- 如果用户进行编辑并且计数在范围内后超出范围,则用户会失去分数
我想我是对的,只是不知道如何完成这个功能。
var check = false;
function titleInc() {
var length = $('#title').val().length;
if (length >= 5 && length <= 10 && !check) {
check = true;
return true;
} else if (check && length < 5 && length > 10) {
// Set the function to return DECREMENT
} else {
return false;
}
$('#title').blur(function () {
var current = parseInt($('#end_val').val(), 10);
if (titleInc()) {
$('#end_val').val(current + 12);
} else if( ){
// THERE NEEDS TO BE A WAY TO DECREMENT
}
});
});
最佳答案
var options = {
increment: 1,
decrement: 2,
doNothing: 3
};
function titleInc() {
var length = $('#title').val().length;
if (length >= 5 && length <= 10 && !check) {
check = true;
return options.increment;
} else if (check && length < 5 && length > 10) {
return options.decrement;
} else {
return options.doNothing;
}
$('#title').blur(function () {
var current = parseInt($('#end_val').val(), 10),
option = titleInc();
if (option === options.increment) {
$('#end_val').val(current + 12);
} else if(option === options.decrement){
$('#end_val').val(current - 12);
}
});
关于jquery - 如何编写一个可以返回 3 个可能选项的 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16529587/