2012-01-26 43 views
0

解除綁定功能的問題我有HTML這樣的:與處理器

<div> 
    <input type="checkbox" id="checkbox", checked="checked"/> 
    <label for="checkbox">Copy values</label> 
</div> 
<div> 
    <input id="source" type="text"/> 
</div> 
<div>  
    <input id="target" type="text"/> 
</div> 

而且我想實現jQuery代碼從source輸入複製值target一個,只有當複選框被選中。這裏是我的代碼:

var checkbox = $("#checkbox"); 
var source = $("#source"); 
var target = $("#target"); 

var bindFunction = function() { 
    var copyValue = function() {console.log("asd"); 
     target.val(source.val()); 
    } 
    if (checkbox.is(":checked")) { 
     source.bind("keyup", copyValue); 
    } 
    else { 
     source.unbind("keyup", copyValue); 
    }  
} 
checkbox.bind("change", bindFunction); 
bindFunction(); 

但是,它並不會達到預期效果 - 由於某種原因,copyValue功能沒有得到解除綁定。我究竟做錯了什麼?

這裏是jsFiddle

+0

而不是綁定和解除綁定也可以使用標誌變量 – jerjer

回答

2

您需要將copyValue函數移到bindFunction函數之外。

這是因爲它每次單擊複選框時都會創建一個新的copyValue實例,因此解除綁定是針對與最初綁定的函數不同的函數運行的。

var copyValue = function() { 
    console.log("asd"); 
    target.val(source.val()); 
} 

var bindFunction = function() {   
    if (checkbox.is(":checked")) { 
     source.bind("keyup", copyValue); 
    } 
    else { 
     source.unbind("keyup", copyValue); 
    }  
} 
checkbox.bind("change", bindFunction); 
bindFunction(); 

http://jsfiddle.net/5b93H/1/

+0

謝謝你,它看起來像我需要一個咖啡:)。 – Przemek