简体   繁体   English

Javascript-寻找替代prependTo的方式,使其不会添加多个项目

[英]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. 当它正确运行时,我会创建一条成功消息,并使用prependTo使其在屏幕上显示。 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." 根据定义,prependTo将“插入到此参数指定的元素的开头。” 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/ 您正在寻找的很可能是html方法,它将使用给定的内容设置匹配元素的innerHTML: http : //api.jquery.com/html/

The usage of html() is slightly different to prependTo() but conceptually the same: html()的用法与prependTo()略有不同,但在概念上是相同的:

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

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

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