选择开始-结束与文本区域

发布于 2024-07-15 20:24:54 字数 151 浏览 2 评论 0原文

我遇到了这个烦人的问题,我似乎无法获取文本区域中所选文本的开始和结束索引,我得到的只是未定义,如下所示:

$('#myarea').selectionStart; // return undefined

我做错了什么吗?

I'm having this annoying problem, I can't seem to get the starting and ending index of the selected text in a textarea, all I get is undefined like this:

$('#myarea').selectionStart; // return undefined

Did I do something wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

因为看清所以看轻 2024-07-22 20:24:54

尝试:

$('#myarea')[0].selectionStart;

为什么? jQuery 选择器不返回实际的 DOM 元素,而是返回包装的 jQuery 集合。 jQuery 使实际的 DOM 元素可以作为数组进行访问,因此如果您想使用第一个匹配的元素(在本例中,是唯一的一个,因为它是通过 ID 实现的),您可以执行上述操作。

Try:

$('#myarea')[0].selectionStart;

Why? A jQuery selector does not return the actual DOM elements but the wrapped jQuery collection. jQuery makes the actual DOM elements accessible as an array, so if you wanted to use the 1st matched element (and in this case, the only one, since it's by ID), you would do the above.

思慕 2024-07-22 20:24:54

从 jQuery 1.6 版本开始,您可以使用 .prop() 方法:

Get:

// always start at 0

var start = $('#myarea').prop('selectionStart');
var end = $('#myarea').prop('selectionEnd');

Set:

$('#myarea').prop('selectionStart', 10);
$('#myarea').prop('selectionEnd', 15);

// or short hand by

$('#myarea').prop({
    'selectionStart': 10,
    'selectionEnd': 15
});

Since jQuery version 1.6, you can use .prop() method:

Get:

// always start at 0

var start = $('#myarea').prop('selectionStart');
var end = $('#myarea').prop('selectionEnd');

Set:

$('#myarea').prop('selectionStart', 10);
$('#myarea').prop('selectionEnd', 15);

// or short hand by

$('#myarea').prop({
    'selectionStart': 10,
    'selectionEnd': 15
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文