jQuery Javascript:如何从 div 或字符串中删除最后一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16540136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: How to remove the last character from a div or a string?
提问by xa.
I have a div with a string of content in it. The content is not stored in a variable and I would like to remove the last character of the text in this div. Any help please?
我有一个包含一串内容的 div。内容未存储在变量中,我想删除此 div 中文本的最后一个字符。请问有什么帮助吗?
More info:
更多信息:
I have a text field, and upon entering text into the text field, the text appears in a div in large writing. When the user hits the back-space key, I want the last character in the div to be deleted. I am mainly using jQuery to achieve this. Here is my code:
我有一个文本字段,在文本字段中输入文本时,文本以大字体显示在 div 中。当用户按下退格键时,我希望删除 div 中的最后一个字符。我主要使用jQuery来实现这一点。这是我的代码:
$(document).ready(function(){
$("#theInput").focus(); //theInput is the text field
$('#theInput').on('keypress', printKeyPress);
function printKeyPress(event)
{
//#mainn is the div to hold the text
$('#mainn').append(String.fromCharCode(event.keyCode));
if(event.keyCode ==8) //if backspace key, do below
{
$('#mainn').empty(); //my issue is located here...I think
}
}
});
I have attempted $('#mainn').text.slice(0,-1);
我已经尝试过 $('#mainn').text.slice(0,-1);
I have also tried storing the value of #theInput in a variable and then printing it, but that didn't work. Any ideas ?
我也试过将#theInput 的值存储在一个变量中然后打印它,但这没有用。有任何想法吗 ?
回答by Mohammad Adil
$('#mainn').text(function (_,txt) {
return txt.slice(0, -1);
});
demo -->
http://jsfiddle.net/d72ML/8/
回答by lintu
Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup
你确定你只想删除最后一个字符。如果用户从单词中间按退格键会怎样。最好从字段中获取值并替换 divs html。按键时
$("#div").html($("#input").val());
回答by Darren
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);