Easiest example I can come up with is a neverending "You clicked" on the first click, then on the second, "You clicked again," and "You clicked again and again, " finally "You clicked again and again...n...and again."
So the first click is normal. Second appends "again". Each time after appends "and again".
I tried doing it with an increasing index but I can't figure out how to multiply a string like it seems I would need to like:
$("button").click(function(){
$(this).text("You clicked" + index++ + "");
But of course that will just return "You clicked 1" etc.
A simple way is to have an array like below and using it..
var myText = ['You clicked', ' again', ' and again'];
var ptr = 0;
$("button").click(function () {
$(this).text(function (i, v) {
return (ptr == 0)?myText[ptr]:(v + myText[ptr]);
});
if (ptr < myText.length - 1) ptr++;
});
Using that array, you can control how many different message you want to append.
$(this).text($(this).text() + " again");
大多数操纵元素属性的jQuery函数都可以用来获取和设置该属性的值,例如$elem.text()
为您提供当前文本值, $elem.text(value)
将其设置为value
。
$(document).ready(function(){
var c = 0;
$('button').click(function(){
if(c == 0) {$(this).append(' again');c++;}
else $(this).append(' and again')
})
})
I suggest this instead of using $(this).text()
twice. :)
Not very elegant, but it works:
var clickCount = 0;
$('.theDiv').click(function() {
var text = ["You clicked"];
if (clickCount > 0) {
text.push(" again");
}
for (var i = 1; i < clickCount; i++)
{
text.push(" and again");
}
text.push("!");
clickCount++;
$('.result').text(text.join(''));
});
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.