[英]Delete char from input using start and end position javascript
I am trying to delete text from input on a following way, and its not working in Mozilla, can anyone help? 我正在尝试通过以下方式从输入中删除文本,但该文本在Mozilla中不起作用,有人可以帮忙吗?
In IE its working fine. 在IE中正常工作。
var start = txt.selectionStart;
var end = txt.selectionEnd;
var selectedStr = txt.value.toString().substring(start, end);
txt.value = txt.value.toString().replace(selectedStr, "");
Mozilla (and other browsers) have a different implementations using document.selection
, window.getSelection()
so you'll need to adjust you code according to those methods/properties and legacy support table. Mozilla(和其他浏览器)使用
document.selection
, window.getSelection()
)具有不同的实现,因此您需要根据这些方法/属性和旧版支持表来调整代码。 You can use many libs out there that normalizes this for you. 您可以在那里使用许多库来对其进行规范化。
Here is a code example that works in webkit: 这是在webkit中工作的代码示例:
var selectedStr = '';
if (window.getSelection) {
var selectedText = window.getSelection().toString()
}
It looks as though you're trying to delete the selected text in a text input. 似乎您正在尝试删除文本输入中的选定文本。 You'll need two different approaches: one for IE < 9 and and one for other browsers that support
selectionStart
and selectionEnd
properties. 您将需要两种不同的方法:一种用于IE <9,另一种用于其他支持
selectionStart
和selectionEnd
属性的浏览器。 Here's how: 这是如何做:
Demo: http://jsfiddle.net/hwG7f/1/ 演示: http : //jsfiddle.net/hwG7f/1/
Code: 码:
function deleteSelected(input) {
input.focus();
if (typeof input.selectionStart == "number") {
var start = input.selectionStart,
end = input.selectionEnd,
val = input.value;
if (start != end) {
input.value = val.slice(0, start) + val.slice(end);
input.setSelectionRange(start, start);
}
} else if (typeof document.selection != "undefined") {
document.selection.createRange().text = "";
}
}
Replacing the value isn't the correct way to approach this. 替换值不是解决此问题的正确方法。 Try taking the chunk of string preceding and following the selection:
尝试选择之前和之后的字符串块:
var start = txt.selectionStart;
var end = txt.selectionEnd;
txt.value = txt.value.substring(0,start) + txt.value.substring(end);
Here is a demonstration: http://jsfiddle.net/BuMUu/1/ 这是一个演示: http : //jsfiddle.net/BuMUu/1/
SelectionStart only works in IE9+. SelectionStart仅在IE9 +中有效。
Sorry, but why don't you just directly set it to "". 抱歉,为什么不直接将其设置为“”。
<input type="text" id="txt" />
<input type="button" value="Clear" id="clear" />
function clear() {
var txt = document.getElementById('txt');
txt.value = "";
}
$('#clear').click(function(){clear()});
var str = "yourString"
str = str.substring(1,str.length-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.