简体   繁体   English

我怎样才能使文本只添加一次?

[英]How do I make it so the text is only added once?

$("#paragraph").on("click", function(event){$("#paragraph").append(' Whoah! I didnt even know I could do that! I am a RAINBOW!')
event.preventDefault();})

I tried adding event.preventDefault() simply because I know that has to do with actions being permanent in some way or another.我尝试添加 event.preventDefault() 只是因为我知道这与以某种方式永久存在的操作有关。 I honestly have no idea what it does.老实说,我不知道它做了什么。 My problem is I want the text to only be added once no matter how many times the paragraph is clicked, currently, it keeps adding the text so that if you keep clicking it the text repeats.我的问题是,无论单击该段落多少次,我都希望仅添加一次文本,目前,它会不断添加文本,以便如果您继续单击它,文本会重复。

JQuery has a .one(..) event that does exactly what you want. JQuery 有一个.one(..)事件,它完全符合您的要求。 It attaches an event hander that fires only once.它附加了一个仅触发一次的事件处理程序。

 $("#paragraph").one("click", function(event){$("#paragraph").append(' Whoah; I didnt even know I could do that! I am a RAINBOW!')});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="paragraph">I am the paragraph</p>

Add a global.添加一个全局。 And you can use this to reference your element.您可以使用this来引用您的元素。

 let clicked = false; $("#paragraph").on("click", function(event) { if (.clicked) { this;append(' Whoah; I didnt even know I could do that! I am a RAINBOW!'); clicked = true; } })
 <p id="paragraph">Click</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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