Пример:
Переключать класс 'highlight' по каждому третьему клику.
"jQuery"
var count = 0;
$("p").click(function(){
$(this).toggleClass("highlight", count++ % 3 == 0);
});
"HTML"
<p class="blue">Click to toggle</p> <p class="blue highlight">highlight</p> <p class="blue">on these</p> <p class="blue">paragraphs</p>
"CSS"
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:yellow; }
"Живой пример jQuery"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="http://slyweb.ru/css/jqueryiframe.css"
rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var count = 0;
$("p").click(function(){
$(this).toggleClass("highlight", count++ % 3 == 0);
});
});
</script>
</head>
<body class="iframe">
<p class="blue">Click to toggle</p>
<p class="blue highlight">highlight</p>
<p class="blue">on these</p>
<p class="blue">paragraphs</p>
</body>
</html>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:yellow; }
</style>
Пример:
Пример для jQuery 1.4. В примере происходит переключение классов happy и sad, в зависимости от того имеют ли они родительский элемент с id bar, переключение происходит с помщью функции обратного вызова.
"jQuery"
$(".foo").click(function () { $(this).toggleClass(function() { if ($(this).parent().is('#bar')) { return 'happy'; } else { return 'sad'; } }); });
"HTML"
<div id="bar"> <p class="foo">Click to toggle </p> </div> <p class="foo">Click to toggle </p>
"CSS"
.foo {
border: 1px solid #cad; width:100px;height:100px; background:#cadceb;}
.happy {
border: 1px solid red; width:100px;height:100px; ; background:yellow;}
.sad {
border: 1px solid blue; width:100px;height:100px; ; background:#cadceb;}
"Живой пример jQuery"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="http://slyweb.ru/css/jqueryiframe.css"
rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".foo").click(function () {
$(this).toggleClass(function() {
if ($(this).parent().is('#bar')) {
return 'happy';
} else {
return 'sad';
}
});
});
});
</script>
</head>
<body class="iframe">
<div id="bar">
<p class="foo">Click to toggle </p>
</div>
<p class="foo">Click to toggle </p>
</body>
</html>
<style>
.foo {
border: 1px solid #cad; width:100px;height:100px; background:#cadceb;}
.happy {
border: 1px solid red; width:100px;height:100px; ; background:yellow;}
.sad {
border: 1px solid blue; width:100px;height:100px; ; background:#cadceb;}
</style>