我正在使用这个脚本每秒都绑定到所有textarea。我正在以这种方式使用它,因为这些textareas是动态加载的(在页面创建并加载此脚本之后)。我希望每次创建一个新的textarea时都会执行一个脚本。我怎么能这样做?
我将此脚本用作自定义标头。我无权访问其余代码。
function autoCorrect(searchString, replaceString) {
$("textarea").keyup(function (e) {
// escape some regex chars
var escapedString = searchString.replace(/([\\.*+?|()\[\]{}])/g, "\\$1");
// finds current cursor position
var pos = $(this).prop("selectionStart");
// this turns the textarea in a string
var text = $(this).val();
//only search for strings just typed
var stringToSearch = text.substring(pos - searchString.length, pos);
if (new RegExp(escapedString).test(stringToSearch) === true) {
//if there is a match put the replaceString in the right place
var newText = text.substring(0, pos - searchString.length) + replaceString + text.substring(pos);
$(this).val(newText);
//adjust the cursor position to the new text
var newpos = pos - searchString.length + replaceString.length;
this.setSelectionRange(newpos, newpos);
}
});
}
setInterval(function(){
autoCorrect("=>", '⇒');
autoCorrect("->", "→");
autoCorrect("+-", "±");
autoCorrect("<=", "≤");
autoCorrect(">=", "≥");
autoCorrect("(c)", "©");
autoCorrect("(e)", "€");
autoCorrect("|__", "⌊");
autoCorrect("__|", "⌋");
autoCorrect("|--", "⊢");
autoCorrect("|==", "⊨");
},1000);
答案 0 :(得分:1)
您应该使用委托事件处理程序,它将自动绑定到稍后添加到DOM的任何textarea:
$("body").on("keyup", "textarea", function() {
// $(this) will be a reference to the current textarea
})
您可能应该使自动更正通过一组定义的值而不是为计时器上的每个值重复调用。只需让keyup事件处理。
var replaceThis = "=>,->,+-".split(",")
var withThis = "⇒,→,±".split(",")
...然后遍历值。