简体   繁体   English

Javascript:如何从div或字符串中删除最后一个字符?

[英]Javascript: How to remove the last character from a div or a string?

I have a div with a string of content in it. 我有一个包含一串内容的div。 The content is not stored in a variable and I would like to remove the last character of the text in this div. 内容不存储在变量中,我想删除此div中文本的最后一个字符。 Any help please? 有什么帮助吗?

More info: 更多信息:


I have a text field, and upon entering text into the text field, the text appears in a div in large writing. 我有一个文本字段,在文本字段中输入文本后,文本以大写字母显示在div中。 When the user hits the back-space key, I want the last character in the div to be deleted. 当用户点击后退空格键时,我希望删除div中的最后一个字符。 I am mainly using jQuery to achieve this. 我主要使用jQuery来实现这一点。 Here is my code: 这是我的代码:

$(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. 我也尝试将#theInput的值存储在一个变量中,然后打印它,但这不起作用。 Any ideas ? 有任何想法吗 ?

$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

demo --> http://jsfiddle.net/d72ML/8/ 演示--> http://jsfiddle.net/d72ML/8/

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. 如果用户从单词的中间按退格键怎么办...更好的是从字段中获取值并替换divs html。 On keyup 关键字

$("#div").html($("#input").val());
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/ http://jsfiddle.net/d72ML/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM