0
我想驗證輸入框中的輸入,所以我需要找到一種方法來刪除添加到字符串中的字符。我的想法是,使用光標位置。我的實現應該可以工作,但每次輸入焦點時都可以看到少數幾個字符的故障。函數獲取光標位置似乎與其定位輸入驗證錯誤
我的小提琴是:http://jsfiddle.net/fallenreaper/TSwyk/
我到底做錯了什麼?當我想驗證時,我不希望它檢查,並刪除錯誤的字符。
我的JavaScript代碼(使用jQuery 1.7.2我相信):
function getCursorPosition(jqueryItem)
{
var input = jqueryItem.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
$("#sel").html(sel);
$("#selLen").html(selLen);
return sel.text.length - selLen;
}
}
$(function(){
alert("loaded");
$("input").on("input", function(){
var cPos = getCursorPosition($(this));
$("#cursorPos").html(cPos);
var FLAG = 'a';
$("#charatpos").html($(this).val().charAt(cPos));
$("#"+$(this).attr("id")+"count").html($(this).val().length);
if($(this).val().charAt(cPos) == FLAG){
var str = $(this).val();
var sArr = str.split("");
sArr.splice(cPos,1);
str = sArr.join("");
$(this).val(str);
}
});
});