admin管理员组文章数量:1405554
I want to add Jack
in the end of a string only one time. How?
$('button').click(function() {
$('div').append('Jack');
});
<script src=".8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
I want to add Jack
in the end of a string only one time. How?
$('button').click(function() {
$('div').append('Jack');
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
In other word, when I click on that button, if Jack is appended, then nothing happens, but if Jack is not exist, then it appends.
Share Improve this question asked Dec 10, 2015 at 22:51 stackstack 10.2k22 gold badges70 silver badges130 bronze badges3 Answers
Reset to default 2$('button').click(function() {
$('div').html('Jack');
});
This will replace whatever is inside the div
$('button').click(function() {
var text = $('div').text();
if(!/Jack/.test(text)){
$('div').append('Jack');
}
});
<script src="https://ajax.googleapis./ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>My name is: </div>
<button>click</button>
Use jQuery's on()
and off()
methods to easily control when event listeners are active.
To add an onclick listener:
$("button").on("click", function(){});
To remove the listener:
$("button").off("click");
In your case, you can put the off()
function call inside of the on()
function's callback. The result is an anonymous function that will run once, on a single click, and then remove itself.
$("button").on("click", function(){
$("div").append("Jack");
$(this).off("click");
}
Or even better, use one()
, which will fire only once per element.
$("button").one("click", function(){
$("div").append("Jack");
}
本文标签: javascriptHow to append something just one time using jQueryStack Overflow
版权声明:本文标题:javascript - How to append something just one time using jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744900513a2631316.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论