簡體   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