jQuery创建并删除< div>通过点击 [英] jQuery create and remove <div> by click
本文介绍了jQuery创建并删除< div>通过点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试编写一个函数,该函数使用户可以在他单击站点的某个区域时创建一个,而当他再次单击该创建的div时,该函数将被删除.我只能以某种方式创建div,当我单击它们时,会创建一个新的div,而不是删除单击的div.我还实现了一个功能,用户可以在该功能中确定是否要创建div或删除div.
Hi I try to wirte a function, which enables the user to create a when he clicks on a certain area of the site, and when he clicks on that created div again, it gets deleted. Somehow I can only create divs and when I click them, a new one is created instead removing of the clicked one. I also implemented a function in which the user can determain if he wants to create a div or delete a div.
<!--changed #button to #conten-->
<div id='content'></div>
<button id='btn'></button>
var i = 0;
var remove = false;
$('#content').click(function(e) {
$('<div></div>').attr({
'id' : i
}).addClass('circle').css({
'top' : e.pageY - 20,
'left' : e.pageX - 20
}).appendTo('#button');
i++;
});
$('.circle').click(function (){
if(remove == true){
$(this).remove();
}
else{
//just to see if it was clicked
$(this).css({'background-color': 'red'});
}
});
$('#btn').toggle(function() {
$('#btn').text('add');
remove = true;
}, function() {
$('#btn').text('remove');
remove = false;
});
推荐答案
工作示例: http://jsfiddle.net/CutPp/
var i = 0;
var remove = true; // added this
$('#button').click(function(e) {
$('<div/>').attr({
'id' : i
}).addClass('circle').css({
'top' : e.pageY - 20,
'left' : e.pageX - 20
}).appendTo('#area'); // append to new container
i++;
});
$('#area').on('click','.circle',function (){ // corrected spelling and changed to on()
if(remove){ // no need to check for == true
$(this).remove();
} else {
//just to see if it was clicked
$(this).css({'background-color': 'red'});
}
});
$('#btn').toggle(function() {
$('#btn').val('add');
remove = true;
}, function() {
$('#btn').val('remove');
remove = false;
});
我做了以下事情:
- 添加了一个变量-
remove
- 使用了 on()而不是单击,因为单击后将div添加到了DOM中绑定
- 对圆的拼写进行了排序
- 为新创建的div创建了一个容器
- added a variable -
remove
- used on() instead of click as the divs are added to the DOM after the click was bound
- sorted the spelling of circle
- created a container for the newly created divs
我的示例HTML
<input type="button" id="button" value="New Div"/> <input type="button" id="btn" value="Add"/><br/>
<span id="area"></span>
这篇关于jQuery创建并删除< div>通过点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文