jQuery .bind multiple events with .text and .css
The following code only displays the last .text upadate. It works as expected with alert(),
$(‘#jTest')
.bind(‘click’,function(event) {
alert(‘Hello!’);
})
.bind(‘click’,function(event) {
alert(‘Hello again!’);
})
.bind(‘click’,function(event) {
alert(‘Hello yet again!’);
});
How can I craft my attempt, to behave as the alert?
$('#jTest')
.bind('click',function(event){
$(this).text("1st Click").css("fontSize","2em");
})
.bind('click',function(event){
$(this).text("2nd Click").css("fontSize","4em");
})
.bind('click',function(event){
$(this).text("3rd Click").css("fontSize","6em");
});
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id = "jTest"><p>Test Data String</p></div>
</body&g开发者_StackOverflow中文版t;
</html>
If you bind event handlers to an element, then all of them are executed when the event occurs. You see the three alerts one after another, because alert
is blocking. I.e. JavaScript continuous executing after you click ok
.
Changing the text or CSS is not blocking, but it is changed three times. It is just so fast that you don't see it.
If you want to change the text on alternate clicks (or execute different callbacks in general), you can use .toggle
[docs]:
$('#jTest').toggle(function(event){
$(this).text("1st Click").css("fontSize","2em");
}, function(event){
$(this).text("2nd Click").css("fontSize","4em");
}, function(event){
$(this).text("3rd Click").css("fontSize","6em");
});
DEMO
This would cycle over the event handlers (you did not mention what you actually want to do).
In your source code all click
events will be handled at once. One solution would be to remember how often it is clicked. Also see my jsfiddle.
var iCounter = 0;
$('#jTest').bind('click', function(event) {
iCounter++;
$(this).text(iCounter + ". Click").css("fontSize", (iCounter * 2) + "em");
});
Here is an example without using toggle
just in case you want a custom logic.
Working demo
$('#jTest')
.bind('click',function(event){
if($(this).data("clickCount") == 0){
$(this).text("1st Click").css("fontSize","2em");
}
})
.bind('click',function(event){
if($(this).data("clickCount") == 1){
$(this).text("2nd Click").css("fontSize","4em");
}
})
.bind('click',function(event){
if($(this).data("clickCount") == 2){
$(this).text("3rd Click").css("fontSize","6em");
}
var clickCount = $(this).data("clickCount")+1;
$(this).data("clickCount", (clickCount > 2?0:clickCount) );
}).data("clickCount", 0);
But I liked Felix Kling's solution if its easy for you to use toggle
. Otherwise my solution can be used anywhere you have click handlers.
精彩评论