2013-11-25 71 views
0

http://pastebin.com/r30Wfvi3JavaScript中,突然的jQuery沒有檢測到我的複選框被選中

突然所有這一切剛剛停止工作。

var showMyLocation = document.createElement('input'); 
showMyLocation.type = "checkbox"; 
showMyLocation.className = "checkboxForRange"; 
showMyLocation.id = "showMyLocation"; 

$$.children("#showMyLocation").html('<p style="float:left">Vis min posisjon :</p>').append(showMyLocation); 

$('#' + showMyLocation.id).change(function() { //location 
     console.log("clicked"); 
     if ($(this).is(":checked")) { 
      console.log("y"); 
      GarageHandler.showPosition(); 
     } else { 
      console.log("n"); 
      GarageHandler.hidePosition(); 
     } 
    }); 

這裏的輸出給定代碼:

"clicked" 
"n", 
"clicked" 
"n", 
"clicked" 
"n", 
"clicked" 
"n", 
etc. 

應該是這樣:

"clicked" 
"y", 
"clicked" 
"n", 
"clicked" 
"y", 
"clicked" 
"n", 
etc. 

有誰知道什麼是錯?

+3

請張貼在問題的代碼,並進行現場演示重現該問題。 – elclanrs

+0

看起來像你有一個容器和輸入字段相同的編號 –

+0

像http://jsfiddle.net/arunpjohny/2EMDR/1/ –

回答

0

從我所看到的你有一個容器元素的ID爲showMyLocation你正在附加複選框,但你的複選框也有相同的ID是無效的,因爲元素的ID必須是唯一的。在你的情況,所以當你註冊更改處理程序時,它已註冊到容器元素而不是複選框,所以this內部的更改處理程序不會引用複選框

您不需要爲輸入元素指定id添加更改處理它,你可以只使用DOM元素引用

$(showMyLocation).change(function() { //location 
    console.log("clicked", this); 
    if (this.checked) { 
     console.log("y"); 
     GarageHandler.showPosition(); 
    } else { 
     console.log("n"); 
     GarageHandler.hidePosition(); 
    } 
}); 

演示:Fiddleanother way

+0

我愛你! 我想我只是真的很累atm:o – andersfylling

相關問題