多个div绑定同一个onclick方法,怎么知道我点击的是哪个呢?我想要点击那个则删除那个!请教!

如题,多个div都添加的有onclick()方法,点击那个 则删除那个?我的怎么没效果啊?
声明:因为插件的原因无法使用$("x").clcik(function(){}); 方法!
JS:

 //删除图片块
    function delImgbox(e){
        console.log( $(this));
        $(this).parent("dt").parent(".Img_box").remove();
        console.log($(this).parent("dt").parent(".Img_box"));
    }

html:

<div class="Imgs_box">
    <dl class="Img_box">
        <dt><img src="1.png"><img onclick="delImgbox(this)" class="close" src="images/icon_close.png"></dt>
        <dd><input class="imgtxt" value="图片1"></dd>
    </dl>
    <dl class="Img_box">
        <dt><img src="2.png"><img onclick="delImgbox(this)" class="close" src="images/icon_close.png"></dt>
        <dd><input class="imgtxt" value="图片2"></dd>
    </dl>
    <dl class="Img_box">
        <dt><img src="3.png"><img onclick="delImgbox(this)" class="close" src="images/icon_close.png"></dt>
        <dd><input class="imgtxt" value="图片3"></dd>
    </dl>
    <dl class="Img_box">
        <dt><img src="4.png"><img onclick="delImgbox(this)" class="close" src="images/icon_close.png"></dt>
        <dd><input class="imgtxt" value="图片4"></dd>
    </dl>
    <div class="Img_box Add_img">
        <div class="addbtn_box">
            <img src="images/Camer.png">
            <input class="upload-file" id="upload-file" type="file" onchange="uploadFile(this,1)" name="file" capture="camera" accept="image/*"     

                cropid="1">
        </div>
        <p>添加项目图片</p>
    </div>
<div id="sub_addimgs">确认修改</div></div>

阅读 6.5k
7 个回答
$(e).parent("dt").parent(".Img_box").remove();

$(e).parent("dt").parent(".Img_box").remove();

function clickAction(e){  
    alert("e.target.tagName : " + e.target.tagName + "\n e.currentTarget.tagName : " + e.currentTarget.tagName);  
} 

注意:target和currentTarget是有区别的
currentTarget始终是监听事件者,而target是事件的真正发出者

1、使用事件委托,$(".imgs_box").on("click",".img_box",function(){
$(this).remove();
})
如果不行的话
2、 $(this).parent("dt").parent(".Img_box").remove()改为 $(this).parents(".Img_box").first().remove()看行不

你可以先把所有的图片用$.each()把所有的图片都遍历一遍。然后

$(".Img_box").each(function(){

$(v).click(function(){
    $(this).remove();
});

});

父级元素绑定事件(事件委托),子级处理$(this)表示当前

$('.parent').on('click', '.child', function(){
    $(this)..........//这里就是你要处理的地方
})

用代理事件,性能更好。
.delegate( selector, eventType, handler )

有个$(this).currentTarget

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题