删除动态添加图像的图钉

时间:2014-01-02 12:03:37

标签: javascript jquery

我正在尝试删除一个图像元素,如果点击,则使用jquery动态添加。 该成就是一个简单的固定地图,如图像应用程序。

HTML:

<div class="imageMapContainer" style="position:relative;" >
    <img class="imageMap" src="image.jpg" style="position:relative;" width="300px" height="300px" />
</div>

使用Javascript:

$(".imageMap").click(function(e){
    var offset = $(this).offset();
    var posLeft = e.clientX - offset.left;
    var posTop = e.clientY - offset.top;

    var pin = "<img onClick='javascript:removePin();' class='imgPin' src='pin.png'" + "style='width:auto;height:auto;position:absolute;left:" + posLeft + ";top:" + posTop + ";' />";
    $(".imageMapContainer").append(pin);    
});

function removePin(){
    //couldn't figure out here
}

我尝试了很多东西但是,我猜不是一个有才华的jscript家伙。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

在点击事件中,您可以添加this以发送对点击元素的引用。 您可以在removePin函数中使用该引用,例如:

$(".imageMap").click(function (e) {
    var offset = $(this).offset();
    var posLeft = e.clientX - offset.left;
    var posTop = e.clientY - offset.top;

    var pin = "<img onClick='javascript:removePin(this);' class='imgPin' src='pin.png'" + "style='width:auto;height:auto;position:absolute;left:" + posLeft + ";top:" + posTop + ";' />";
    $(".imageMapContainer").append(pin);
});

function removePin(elm) {
    $(elm).remove();
}

答案 1 :(得分:0)

使用.on

$('.imageMapContainer').on('click', '.imgPin', function() { 
     $(this).remove(); 
});
相关问题