JavaScript/jQuery-替换输入文本中的文本 [英] JavaScript/jQuery - replace text in input text

查看:105
本文介绍了JavaScript/jQuery-替换输入文本中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个输入字段:<input type="text" id="id0"/>.我想用我的文本动态替换当前选择的文本.使用jQuery或javascript实现此目标的最佳方法是什么?

Let's say we have an input field: <input type="text" id="id0"/>. I would like to dynamically replace the current selection of the text with my text. What is the best way to achieve that using jQuery or javascript?

更新:

我的意思是:用户键入文本并选择其中的一部分,然后按下按钮以将所选部分替换为另一指定文本.

I meant: the user types the text and selects part of it, then presses a button to replace the selected section with another specified text.

问候,拉法尔

推荐答案

大多数浏览器在文本输入和文本区域上支持selectionStartselectionEnd属性.但是,IE< 9没有.您可以为此使用我的 Rangy输入插件,它可以规范IE< 9的缺乏支持,并提供了方便的方法来处理文本输入和文本区域中的选择.使用它,代码将是:

Most browsers support selectionStart and selectionEnd properties on text inputs and textareas. However, IE < 9 does not. You could use my Rangy inputs plug-in for this, which normalizes the mess of IE < 9's lack of support and provides convenient methods for dealing with selections in text inputs and textareas. Using it, the code would be:

$("#id0").replaceSelectedText("SOME NEW TEXT");

如果文本框没有焦点,则需要先将其聚焦:

If the text box does not have the focus, you'll need to focus it first:

$("#id0").focus();

这篇关于JavaScript/jQuery-替换输入文本中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆