开发者

removing part of string UPDATED

开发者 https://www.devze.com 2022-12-10 16:39 出处:网络
www.powersource.se The last link, \"Add some stuff\" doesn\'t work properly. It\'s supposed to add a bit of text when you press it and then remove the text when you press it again. I\'ve made the add

www.powersource.se

The last link, "Add some stuff" doesn't work properly. It's supposed to add a bit of text when you press it and then remove the text when you press it again. I've made the add-part work, but I haven't managed to make the remove-part.

function add_module(title, text)
{
container = document.getElementById('text-main');
the_text ='<div class="text-header" id="added-text-header">' + title + '</div><div id="added-text">' + text + '</div>';
if(container.innerHTML != container.innerHTML + the_text)
{
container.innerHTML = container.innerHTML + the_text;
}else if(container.div.innerHTML == container.innerHTML + the_text)
{
text_container = container.getElementById('added-text-header');
parent = text_container.parentNode;
parent.removeChild(text_container);
text_container = container.getElementById('added-text');
parent = text_container.parentNode;
parent.remo开发者_Go百科veChild(text_container);
}
}


You're using + to add text in. That's how JavaScript concatenates two strings.

The problem comes when you try to use - to remove. That won't work. The minus sign is for subtracting numbers, not for taking something away from a string.

I'd suggest using jQuery or another JavaScript library that has good cross-browser DOM manipulation. When you insert more text in, use a function to add a chunk of HTML. Use the p tag: <p>some text</p>. Then you'll be able to hunt down the p tags and delete the last one.


When you say string1 + string2 you're actually creating a brand new string, + is just shorthand for "mash these two together."

If you want to be able to add and remove that text you'll have to do it another way. The real issue is that once you've concatenated the strings together you have no idea which part of the string is the original, and which part is the user's.

In jQuery you can use DOM manipulation to better handle this. First I would put your div tags with the text-header and the text inside your container, but leave them empty. That way you don't have to create them on the fly. Then (assuming your text div has a class of "text-body"):

var textHeader = $("#text-main .text-header");
var textBody = $("#text-main .text-body");

//If the header doesn't contain the title set it, otherwise remove it
if(textHeader.text() != title) {
    textHeader.text(title)
} else {
    textHeader.text("");
}

//If the text body doesn't contain the text set it, otherwise remove it
if(textBody.text() != text) {
    textBody.text(text)
} else {
    textBody.text("");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消