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 badges
Add a ment  | 

3 Answers 3

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