2013-01-01 71 views
0

我有這個代碼的問題: 如果你點擊「已上傳文本」兩次,你會得到2個div的內容爲「hello2」 和一個「hello3」,但對於一些resone當你點擊它們時,它們會打開同一個塊。 insted的有他們每個人開自己的塊的。(我想保持它動態地創建。)感謝您的幫助使用jQuery和風格動態

<!DOCTYPE html> 
<html> 
<head> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> 
</script> 
<script> 
var k=1; 
$(document).ready(function(){ 
    $("#flip").click(function(){ 
    $("#panel").slideToggle("slow"); 
    }); 
}); 
function appendText() 
{ 
    k=k+1; 
    var css = '#flip'+k+' { padding:5px; text-align:center; background-color:#ffff00; border:solid 1px #c3c3c3;}', 
    head = document.getElementsByTagName('head')[0], 
    style = document.createElement('style'); 
    style.type = 'text/css'; 
    if (style.styleSheet){ 
    style.styleSheet.cssText = css; 
    } else { 
    style.appendChild(document.createTextNode(css)); 
    } 

    head.appendChild(style); 

    var css = '#panel'+k+'{padding:50px;display:none;text-align:center; background- color:#'+k+''+k+''+k+''+k+''+k+''+k+'; border:solid 1px #c3c3c3;}', 
    head = document.getElementsByTagName('head')[0], 
    style = document.createElement('style'); 
    style.type = 'text/css'; 
    if (style.styleSheet){ 
    style.styleSheet.cssText = css; 
    } else { 
    style.appendChild(document.createTextNode(css)); 
    } 
    head.appendChild(style); 

    var flip2 = document.createElement("div"); 
    flip2.innerHTML = "Hello"+k; 
    flip2.id = ("flip"+k); 

    var panel2= document.createElement("div"); 
    panel2.innerHTML = "Hello"+k; 
    panel2.id = ("panel"+k); 

    document.body.appendChild(flip2); 
    document.body.appendChild(panel2); 

    $(document).ready(function(){ 
    $(("#flip"+k)).click(function(){ 
     $(("#panel"+k)).slideToggle("slow"); 
    }); 
    }); 
} 
</script> 

<style type="text/css"> 
#panel,#flip 
{ 
padding:5px; 
text-align:center; 
background-color:#e5eecc; 
border:solid 1px #c3c3c3; 
} 
#panel 
{ 
padding:50px; 
display:none; 
} 
</style> 
</head> 
<body> 

<p>This is a paragraph.</p> 
<button onclick="appendText()">Append text</button> 


<div id="flip">Click to slide the panel down or up</div> 
<div id="panel">Hello world!</div> 

</body> 
</html> 
+1

嘗試在http://jsfiddle.net/ – phnkha

+0

上進行演示用變量'k'做什麼? –

+0

@Nate它的存在使代碼無法正常工作:-) – Pointy

回答

2

的問題是,您的變量k全球。當它改變時,你的事件處理程序都會看到相同的值(前2個,後3個,然後4個等)。

設置你的事件處理程序是這樣的:

(function(kk) { 
    $(("#flip"+kk)).click(function(){ 
    $(("#panel"+kk)).slideToggle("slow"); 
    }); 
})(k); 

沒有理由使用「準備」處理程序,在所有增加的元素在函數內部。

+0

你明白'k'是什麼! – jadkik94

+0

謝謝!現在它工作 – user1832791