gpt4 book ai didi

javascript - jQuery event.stopPropagation() 和事件问题

转载 作者:行者123 更新时间:2023-12-03 12:08:19 25 4
gpt4 key购买 nike

我正在创建一个 jQuery 脚本,在单击事件上向 map 添加图钉,问题是我需要该事件仅在 map 上工作,而不是在他的儿子上工作。

这是我的代码:

$("div#map").click(function (e) {
$('<div class="pin"></div>').css({
left: a_variable,
top: another_variable
}).appendTo(this);

$("div.pin").click(function (e) { e.stopPropagation(); });
})

另一个问题是,在这段代码下我有这样的东西:

$("div.pin").mousedown(function (e) {
if(e.which == 1) {
console.log("down");
moving = true;
$(this).addClass("moving");
} else if(e.which == 3) {
console.log("right");
}
});

这也适用于脚本加载后创建的引脚吗?

JsFiddle:http://jsfiddle.net/vB2Gb/

最佳答案

我对您的代码进行了一些调整:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/vB2Gb/1/

$(function () {
var $map = $("div#map");
$map.click(function (e) {
var $pin = $('<div class="pin"></div>').css({
left: (((e.pageX + 3 - $map.position().left) * 100) / $map.width()) + "%",
top: (((e.pageY - 10 - $map.position().top) * 100) / $map.height()) + "%"
});
$pin.appendTo($map);
})
$map.on('click', "div.pin", function (e) {
e.stopPropagation();
});

var moving = false;

var pin_id;
var pin_left;
var pin_top;

$map.on('mousedown', "div.pin", function (e) {
if (e.which == 1) {
console.log("down");
moving = true;
$(this).addClass("moving");
} else if (e.which == 3) {
console.log("right");
}
});

$map.on('contextmenu', "div.pin", function (e) {
return false;
});

$(document).mousemove(function (e) {
if (moving) {
if (e.pageX <= $map.position().left) {
pin_left = 0;
} else if (e.pageY <= $map.position().top) {
pin_top = 0;
} else {
console.log("moving");
pin_id = 1;
pin_left = (((e.pageX + 3 - $map.position().left) * 100) / $map.width());
pin_top = (((e.pageY - 10 - $map.position().top) * 100) / $map.height());
$(".moving").css("left", pin_left + "%");
$(".moving").css("top", pin_top + "%");
}
}
});

$(document).mouseup(function (e) {
if (moving) {
console.log("up");
moving = false;
$(".moving").removeClass("moving");
dbMovePin(pin_id, pin_left, pin_top);
}
});

});

function dbMovePin(pin_id, pin_left, pin_top) {
$.post(
"mapsave.php", {
action: "move_pin",
id: pin_id,
left: pin_left,
top: pin_top
},

function (data, status) {
//alert("Data: " + data + "\nStatus: " + status);
});
}

这包括对鼠标按下事件和图钉单击事件使用委托(delegate)事件(打开)。为 map 等共享单个变量

关于javascript - jQuery event.stopPropagation() 和事件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25080897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com