我試圖做一個切換功能,所以當你點擊一個鏈接時,它會做一件事,當你再次點擊相同的鏈接時,它會做另一件事。我的問題是,我使用的是最新版本的Jquery,看起來切換事件是Deprecated。在2個函數之間切換
我在嘗試使用它之前,我發現它已被棄用。
$('#edit a').toggle(
function(){
editList();
},
function(){
addList();
});
它在文檔中說它已經被綁定點擊。
我試圖做一個切換功能,所以當你點擊一個鏈接時,它會做一件事,當你再次點擊相同的鏈接時,它會做另一件事。我的問題是,我使用的是最新版本的Jquery,看起來切換事件是Deprecated。在2個函數之間切換
我在嘗試使用它之前,我發現它已被棄用。
$('#edit a').toggle(
function(){
editList();
},
function(){
addList();
});
它在文檔中說它已經被綁定點擊。
微jQuery插件:
jQuery.fn.clickToggle = function(a,b) {
var ab = [b,a];
return this.on("click", function(){ ab[this._tog^=1].call(this); });
};
// USE LIKE:
$("button").clickToggle(function() {
console.log("AAA");
}, function() {
console.log("BBB");
}); // Chain here other jQuery methods to your selector
從這裏我的答案兩者https://stackoverflow.com/a/21520499/383904
還有其他的方法來切換的狀態/值:
var editAdd = [editList, addList], // store your function names into array
c = 0; // toggle counter
function editList(){ // define function
alert('EDIT');
}
function addList(){ // define function
alert('ADD');
}
$('#edit a').click(function(e){
e.preventDefault();
editAdd[c++%2](); // toggle array index and use as function
// % = Modulo operator
});
其中,代替模運算%
可以使用
位異或操作^
,如:[c^=1]
使用Array.reverse()
LIVE DEMO
var editAdd = [editList, addList];
function editList(){
alert('EDIT');
}
function addList(){
alert('ADD');
}
$('#edit a').click(function(e){
e.preventDefault();
editAdd.reverse()[0]();
});
反向將在每次點擊時反轉我們的陣列,我們所需要做的就是取0索引值[0]
並運行該函數名稱[0]()
。
我喜歡這種簡單。 – 2013-03-24 20:22:19
@Howdy_McGee不像我兩年後的回答那麼簡單。結帳我的關閉。 – t3dodson 2015-05-22 07:43:23
不優雅,但快速修復:
$('#edit a').click({
if($(this).data('toggleState') == 1) {
toggleState = 0;
addList();
}
else {
toggleState = 1;
editList();
}
$(this).data('toggleState', toggleState);
return false;
});
從它的外觀來看,沒有解決方案會變得優雅。 – 2013-03-24 20:20:31
所有你需要做的是有一個變量,或屬性,指示執行何種功能,例如,使用自定義data-switch
屬性:
$('a').click(function(e){
e.preventDefault();
var that = $(this);
switch (that.data('switch')){
case 'a':
// do something in situation 'a'
console.log('Function one');
that.data('switch','b');
break;
case 'b':
// do something in situation 'b'
console.log('Function two');
that.data('switch','a');
break;
}
});
短和清潔
var toggle = [addList, editList];
$('#edit a').click({
var state = +$(this).data('toggle');
toggle[state]();
$(this).data('toggle',(1-state));
return false;
});
見我對這個here
該解決方案的答案創建構成每次調用時兩者之間兩個功能交替切換功能。
var toggle = function (a, b) {
var togg = false;
return function() {
// passes return value back to caller
return (togg = !togg) ? a() : b();
};
};
與
$('#btn').on('click', toggle (function(){
return editList();
}, function(){
return addList();
}));
很酷。另請參閱使用'.clickToggle()'微型jQuery插件這個不錯的方法:http://stackoverflow.com/a/21520499/383904或者更好的方法 – 2015-05-22 09:23:21
@ RokoC.Buljan這真的很類似。我更喜歡這種方式,因爲它不會在運行時更改任何對象。並沒有jQuery的依賴。 – t3dodson 2015-05-22 18:11:55
應用它我不知道這個問題是在這裏。你在問怎麼做? HTTP://forum.jquery。com/topic/beginner-function-toggle-deprecated-what-to-use-instead簡單的搜索。 – 2013-03-24 20:13:37