简体   繁体   中英

Javascript - looking for an alternative to prependTo so that it doesn't add multiple items

I have some code. When it runs correctly, I create a success message and use prependTo in order to display it on the screen. The problem is that when the user does their successful action twice, I end up with two success messages.

Is there a way to overwrite my success message. Here is how I currently handle it in my code:

  $((is_error ? "<p class=' alert alert-error'>"+message+"</p>)" : "<p class=' alert alert-success'>"+message+"</p>")).prependTo("#feedback-container");

Thanks!

可以使用html代替prependTo ,因此您不必先添加而是替换消息容器的内容:

$("#feedback-container").html(is_error ? "<p class=' alert alert-error'>"+message+"</p>" : "<p class=' alert alert-success'>"+message+"</p>");

You can use simply this :

$("#feedback-container").html((is_error ? "<p class=' alert alert-error'>"+message+"</p>)" : "<p class=' alert alert-success'>"+message+"</p>"));

So the entire content of your container is replaced.

$("#feedback-container").children(".alert:first-child").remove().end().prepend( "stuff" );

工作演示http://jsfiddle.net/uVVYN/

By definition prependTo will "inserted at the beginning of the element(s) specified by this parameter." In other words, it will insert but not replace .

What you are looking for is most likely the html method that will set the innerHTML of the matched element with the given content: http://api.jquery.com/html/

The usage of html() is slightly different to prependTo() but conceptually the same:

 $("#feedback-container").html((is_error ? "<p class=' alert alert-error'>"+message+"</p>)" : "<p class=' alert alert-success'>"+message+"</p>"));

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