简体   繁体   中英

How to slice text dynamically added to an element?

I'm making an app where users can type messages. It has its own keyboard, and you click on each letter to type in the box. I also have a delete button, where you can click on it to delete the last letter of what you typed. However, my jQuery isn't working.

Here's my Codepen .

JQuery:

$(document).ready(function () {
var myArray = ['Q', 'W', 'E', 'R', 'T', 'Y']
$.each( myArray, function( i, item ) {
var key = "<div class='letter'>" + item + "</div>";
$(".keyboard").append(key);
});

$('.letter').click(function (){
$('#text').append($(this).text());
});

$("#delete").click(function() {
var str = $('#text').text();
str.innerHtml.slice(0,-1);
});
});

I also followed this post on modifying link elements, but their solution didn't work for me.

Can anyone help me figure out what's going on? Thanks so much.

You were missing on 2 parts. 1. str is already a string and innerHTML is not a property of string 2. After you splice it you need to set it back in html

Hence, you need to update your delete function to following

$("#delete").click(function() {
    var str = $('#text').text();
    $('#text').text(str.slice(0,-1));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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