【发布时间】:2014-08-04 02:00:24
【问题描述】:
我正在尝试在 contenteditable div(如 here 所示)中将一些愚蠢的引号动态转换为弯引号,使用以下内容:
$("#editor").on("keyup", ".content", function () {
$(".content").html(function() {
var start = this.selectionStart, end = this.selectionEnd;
return $(this).html()
.replace(/'\b/g, "\u2018") // opening single
.replace(/\b'/g, "\u2019") // closing single
.replace(/"\b/g, "\u201c") // opening double
.replace(/\b"/g, "\u201d") // closing double
.replace(/--/g, "\u2014") // em-dash
.replace(/\b\u2018\b/g, "'"); // handle conjunctions
this.setSelectionRange(start, end);
});
// other stuff happens here...
});
return 位单独工作正常,但在每次击键后将插入符号位置移回潜水的开始,这显然是不可取的。但是试图保持插入符号的位置(使用看到的一些代码 here)会在 JSHint 中抛出 Unreachable 'this' after 'return',因此实际上并没有在浏览器中做任何事情。有人可以在这里指出我正确的方向吗?
【问题讨论】:
-
1.定义名为 resultHTML 的变量。 2.将您编辑的html存储在其中。 3. 执行 selectionRange 的东西。 4. 返回resultHTML。
-
当我这样做时,我得到一个错误:
TypeError: 'undefined' is not a function (evaluating 'this.setSelectionRange(start,end)')。不知道那里发生了什么。 -
setSelectionRange 是 HTMLInputElement 的一个函数。在您的代码中,
this指向其他内容。试试$(yourInputElement).setSelectionElement(...);(只是一个快速而肮脏的尝试......)。 -
感谢您迄今为止的帮助,但我找不到有关该 setSelectionElement 方法的任何文档 - 您能指出我的文章或(甚至更好)某个工作示例吗?
标签: javascript jquery