jQuery 클릭 / 두 기능 간 전환
나는 무언가를 클릭 할 때 두 개의 별도의 작업 / 기능 / "코드 블록"을 실행하고 같은 것을 다시 클릭하면 완전히 다른 블록을 실행하는 방법을 찾고 있습니다. 나는 이것을 합쳤다. 더 효율적이고 우아한 방법이 있는지 궁금합니다. 나는 jQuery .toggle () 에 대해 알고 있지만 약간 짜증납니다.
여기서 일하기 : http://jsfiddle.net/reggi/FcvaD/1/
var count = 0;
$("#time").click(function() {
count++;
//even odd click detect
var isEven = function(someNumber) {
return (someNumber % 2 === 0) ? true : false;
};
// on odd clicks do this
if (isEven(count) === false) {
$(this).animate({
width: "260px"
}, 1500);
}
// on even clicks do this
else if (isEven(count) === true) {
$(this).animate({
width: "30px"
}, 1500);
}
});
jQuery에는 .toggle(). 다른 하나는 [문서]를 정확히 클릭 이벤트를 원하는 것을.
참고 : 적어도 jQuery 1.7 이후이 버전 .toggle은 더 이상 사용되지 않는 것 같습니다. 아마도 정확히 그 이유, 즉 두 가지 버전이 존재하기 때문일 것입니다. .toggle요소의 가시성을 변경하는 데 사용 하는 것은 더 일반적인 용도 일뿐입니다. 이 메소드는 jQuery 1.9에서 제거되었습니다 .
다음은 플러그인과 동일한 기능을 구현할 수있는 방법의 예입니다 (하지만 내장 버전과 동일한 문제를 노출 할 수 있습니다 (문서의 마지막 단락 참조)).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
(면책 조항 : 이것이 최고의 구현이라고 말하지 않습니다! 성능 측면에서 개선 될 수있을 것입니다)
그런 다음 다음과 같이 호출하십시오.
$('#test').clickToggle(function() {
$(this).animate({
width: "260px"
}, 1500);
},
function() {
$(this).animate({
width: "30px"
}, 1500);
});
업데이트 2 :
그 동안 나는 이것에 대한 적절한 플러그인을 만들었습니다. 임의의 수의 함수를 허용하며 모든 이벤트에 사용할 수 있습니다. GitHub에서 찾을 수 있습니다 .
.one () 문서.
대답하기에는 매우 늦었지만 코드가 가장 짧고 도움이 될 것이라고 생각합니다.
function handler1() {
alert('First handler: ' + $(this).text());
$(this).one("click", handler2);
}
function handler2() {
alert('Second handler: ' + $(this).text());
$(this).one("click", handler1);
}
$("div").one("click", handler1);
function handler1() {
$(this).animate({
width: "260px"
}, 1500);
$(this).one("click", handler2);
}
function handler2() {
$(this).animate({
width: "30px"
}, 1500);
$(this).one("click", handler1);
}
$("#time").one("click", handler1);
Micro jQuery 플러그인
자신의 체인 가능한 clickToggle jQuery Method를 원한다면 다음과 같이 할 수 있습니다.
jQuery.fn.clickToggle = function(a, b) {
return this.on("click", function(ev) { [b, a][this.$_io ^= 1].call(this, ev) })
};
// TEST:
$('button').clickToggle(function(ev) {
$(this).text("B");
}, function(ev) {
$(this).text("A");
});
<button>A</button>
<button>A</button>
<button>A</button>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
간단한 기능 토글 러
function a(){ console.log('a'); }
function b(){ console.log('b'); }
$("selector").click(function() {
return (this.tog = !this.tog) ? a() : b();
});
더 짧게 만들고 싶다면 ( 왜 그렇죠 ?! ) Bitwise XOR * Docs 연산자를 다음과 같이 사용할 수 있습니다 .
DEMO
return (this.tog^=1) ? a() : b();
그게 다야.
트릭은 thisObject boolean속성 을 설정하고 부정 ( )을 tog사용하여 토글 하고 필요한 함수 호출을 조건부 연산자 에 넣는 것입니다.tog = !tog
?:
OP의 예 (여러 요소 포함)에서 다음과 같이 보일 수 있습니다.
function a(el){ $(el).animate({width: 260}, 1500); }
function b(el){ $(el).animate({width: 30}, 1500); }
$("selector").click(function() {
var el = this;
return (el.t = !el.t) ? a(el) : b(el);
});
또한 : 다음 과 같이 -toggle 을 저장할 수도 있습니다 .
DEMO :
$("selector").click(function() {
$(this).animate({width: (this.tog ^= 1) ? 260 : 30 });
});
그러나 그는 OP의 정확한 요청이 아니 었습니다. looking for a way to have two separate operations / functions
Array.prototype.reverse 사용 :
참고 : 이것은 현재 Toggle 상태를 저장하지 않고 Array의 함수 위치를 반전시킵니다 (사용이 있습니다 ...)
a, b 함수를 배열 안에 저장 하고, onclick 을 클릭 하면 배열 순서를 반대로하고 array[1]함수를 실행하기 만하면 됩니다.
function a(){ console.log("a"); }
function b(){ console.log("b"); }
var ab = [a,b];
$("selector").click(function(){
ab.reverse()[1](); // Reverse and Execute! // >> "a","b","a","b"...
});
일부 매쉬업!
toggleAB()두 함수를 포함 할 멋진 함수 를 만들어 Array에 넣고 배열 의 끝에 참조 에서 함수에 전달 된 속성 0 // 1에 따라 각각 [ ] 함수를 실행하면됩니다 .togthis
function toggleAB(){
var el = this; // `this` is the "button" Element Obj reference`
return [
function() { console.log("b"); },
function() { console.log("a"); }
][el.tog^=1]();
}
$("selector").click( toggleAB );
값을 토글하기 만하면 표시된 코드에 대해 다음과 같이 할 수 있습니다.
var oddClick = true;
$("#time").click(function() {
$(this).animate({
width: oddClick ? 260 : 30
},1500);
oddClick = !oddClick;
});
나는 이것을 두 기능 사이의 토글 효과를 만드는 데 사용했습니다.
var x = false;
$(element).on('click', function(){
if (!x){
//function
x = true;
}
else {
//function
x = false;
}
});
jQuery 1.9에서 제거 된 이유가 있기 때문에 토글 메서드를 구현해야한다고 생각하지 않습니다.
대신 jQuery에서 완전히 지원하는 toggleClass를 사용하는 것이 좋습니다.
function a(){...}
function b(){...}
예를 들어 이벤트 트리거가 onclick이라고 가정 해 보겠습니다.
첫 번째 옵션 :
$('#test').on('click', function (event) {
$(this).toggleClass('toggled');
if ($(this).hasClass('toggled')) {
a();
} else{
b();
}
}
핸들러 함수를 매개 변수로 보낼 수도 있습니다.
두 번째 옵션 :
$('#test').on('click',{handler1: a, handler2: b}, function (event) {
$(this).toggleClass('toggled');
if ($(this).hasClass('toggled')) {
event.data.handler1();
} else{
event.data.handler2();
}
}
boolean isEven을 유지하는 것이 전부 라면 클래스 isEven가 요소에 있는지 확인한 다음 해당 클래스를 토글하는 것을 고려할 수 있습니다 .
count와 같은 공유 변수를 사용하는 것은 일종의 나쁜 습관입니다. 그 변수의 범위가 무엇인지 스스로에게 물어보고, 페이지에서 토글하고 싶은 항목이 10 개 있는지 생각해보세요. 10 개의 변수를 만들까요, 아니면 상태를 저장할 배열이나 변수를 만들까요? 아마 아닐 것입니다.
Edit:
jQuery has a switchClass method that, when combined with hasClass can be used to animate between the two width you have defined. This is favourable because you can change these sizes later in your stylesheet or add other parameters, like background-color or margin, to transition.
Use a couple of functions and a boolean. Here's a pattern, not full code:
var state = false,
oddONes = function () {...},
evenOnes = function() {...};
$("#time").click(function(){
if(!state){
evenOnes();
} else {
oddOnes();
}
state = !state;
});
Or
var cases[] = {
function evenOnes(){...}, // these could even be anonymous functions
function oddOnes(){...} // function(){...}
};
var idx = 0; // should always be 0 or 1
$("#time").click(function(idx){cases[idx = ((idx+1)%2)]()}); // corrected
(Note the second is off the top of my head and I mix languages a lot, so the exact syntax isn't guaranteed. Should be close to real Javascript through.)
modifying the first answer you are able to switch between n functions :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus.com®">
<!-- <script src="../js/jquery.js"></script> -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<title>my stupid example</title>
</head>
<body>
<nav>
<div>b<sub>1</sub></div>
<div>b<sub>2</sub></div>
<div>b<sub>3</sub></div>
<!-- .......... -->
<div>b<sub>n</sub></div>
</nav>
<script type="text/javascript">
<!--
$(document).ready(function() {
(function($) {
$.fn.clickToggle = function() {
var ta=arguments;
this.data('toggleclicked', 0);
this.click(function() {
id= $(this).index();console.log( id );
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(ta[id], this)();
data.toggleclicked = id
});
return this;
};
}(jQuery));
$('nav div').clickToggle(
function() {alert('First handler');},
function() {alert('Second handler');},
function() {alert('Third handler');}
//...........how manny parameters you want.....
,function() {alert('the `n handler');}
);
});
//-->
</script>
</body>
</html>
참고URL : https://stackoverflow.com/questions/4911577/jquery-click-toggle-between-two-functions
'IT박스' 카테고리의 다른 글
| Visual Studio는 잘 컴파일되지만 여전히 빨간색 선이 표시됩니다. (0) | 2020.10.28 |
|---|---|
| link_to 메소드 및 Rails의 클릭 이벤트 (0) | 2020.10.28 |
| 배열에서 모든 고유 요소를 가져 오는 jQuery 함수? (0) | 2020.10.28 |
| IgnoreCase를 사용하여 C # Switch 문을 만드는 방법 (0) | 2020.10.28 |
| NSSortDescriptor를 사용하여 배열을 정렬하고 싶습니다. (0) | 2020.10.28 |