我尝试创建一个在$(document).ready()事件上运行的函数,并且它支持创建一个新的div。现在当我想创建另一个div时,具有相同的DOM和Class属性但是在不同的位置上,这就是问题......
//Updating z-index in css duo to more than 1 note
var zIndex = 10000;
function updateIndex(element){
zIndex = zIndex+1; //Counter, '++' = +1
$(element).css('z-index', zIndex);
}
$("div .makeNew").on("click", function(e) {
updateIndex(this);
});
$(".note input textarea").on("click", function(e) {
updateIndex(this);
});
function MakeNewNote(){
zIndex = zIndex + 1;
$('#content').css('z-index', zIndex).append("<div class="note" ><div id="controlsTop"><div class="deleteNote">X</div><div class="makeNew">+</div></div><input value="My Note" /><textarea value="I Have something to save" cols="20" name="S1" rows="1"></textarea><div id="controlsExtra hidden"><div class="controlBold"></div><div class="controlItalic"></div><div class="controlUnderlined"></div><div class="controlLeft"></div><div class="controlCenter"></div><div class="controlRight"></div><div class="controlBigFont"></div><div class="controlSmallFont"></div></div> <!-- controlsExtra --></div> <!-- note -->");
$('.note').draggable();
}
function DeleteThisNote(){
$('.note').remove();
}
$(document).ready(MakeNewNote); // Creates a note just at startup
$(document).ready(function(){
$('div .makeNew').on('click', MakeNewNote); // Creates a new note, enables button press inside the note
$('div .deleteNote').one('click', DeleteThisNote); // Removes current note
});
/* CSS DOCUMENT */
/* Autor: Ismar Hadzic */
/* Description: Main style for Sticky Notes */
/* Licensed to WiKey inc. All rights reserverd 2015 */
.note {
width: 200px; height: 200px;
background:#FFFFCC;
margin:15px;
}
.note .controlsTop {
background:#FFFF66;
padding-top:50px;
margin-left:10px;
}
.note .controlsTop .deleteNote {
width:10px;
display:block;
float:left;
margin-left:5px;
}
.note .controlsTop .makeNew {
width:10px;
display:block;
float:left;
margin-left:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
// Should output here
</div>
答案 0 :(得分:0)
以下两项更改可以解决您的问题:
首先,仅仅初始化刚刚添加的div.note
...而不是所有现有的:
将$('.note').draggable();
更改为:
$('.note').last().draggable();
其次,删除相应的div.note
:
将$('.note').remove();
更改为:
$(this).closest('.note').remove();
<强>更新强>
在 DOM ready 事件之后创建的元素需要委派事件才能使其工作:
$('#content').on('click', 'div .makeNew', MakeNewNote);
$('#content').one('click', 'div .deleteNote', DeleteThisNote);