这让我感到困惑。这是我试图实现的伪代码,我需要使用click作为与我构建的触摸手势的钩子。
if body is clicked {
if click has touched .circle {
remove circle;
}
else {
create circle;
}
}
答案 0 :(得分:4)
修改:自从撰写以下答案后,delegate
已被on
取代,而event bubbling应该被取代。
您可以(ab)使用发生的delegate。您将点击监听器附加到每个具有类circle
的div(将使用jQuery的jQuery.fn.clone方法),并且一旦处理完该事件,取消冒泡,所以它不会到达身体点击监听器。
而且,在身体监听器上,只需附加圆圈。
这样的事情:
var circle = $("<div>").addClass("circle").text("Circle!");
$("body").click(function() {
$(this).append(circle);
});
$("body").delegate(".circle", "click", function(e) {
$(this).remove();
//To stop the bubbling up
e.stopPropagation();
return false;
});
或者,更简单的方法,只需使用event.target
检查点击事件的目标:
var circle = $("<div>").addClass("circle").text("Circle!");
$("body").click(function(e) {
var target = $(e.target);
if (target.hasClass("circle")) {
target.remove();
}
else {
$(this).append(circle);
}
});
注意:因为我创建了circle
div作为变量,所以只能有一个。如果你不想那样,你可以使用{{3}},或者只是当场制作你需要的东西。
答案 1 :(得分:2)
尝试:
$(document).ready(function () {
$(this).click(function (e) {
var element = $(e.target);
// do your job with element, for example you can retrieve its "id"
alert(element.attr("id"));
});
});
答案 2 :(得分:1)
您需要使用活动的target
属性。
$('body').click(function (e) {
if(e.target.hasClass("circle")) {
$(e.target).remove();
} else {
// Create circle
}
});
答案 3 :(得分:0)
它不会完全响应您的请求,但它会为您提供想法。
我希望这有很多原因(更容易编码,符合人体工程学的效率等):with a fake button。
此外,您可以执行可放置区域来创建和删除项目(http://docs.jquery.com/UI/Droppable)。