繁体   English   中英

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

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

我有一个包含一串内容的div。 内容不存储在变量中,我想删除此div中文本的最后一个字符。 有什么帮助吗?

更多信息:


我有一个文本字段,在文本字段中输入文本后,文本以大写字母显示在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
        }
    }

});

$('#mainn').text.slice(0,-1);

我也尝试将#theInput的值存储在一个变量中,然后打印它,但这不起作用。 有任何想法吗 ?

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

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

你确定要删除最后一个字符吗? 如果用户从单词的中间按退格键怎么办...更好的是从字段中获取值并替换divs html。 关键字

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

http://jsfiddle.net/d72ML/

暂无
暂无

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

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