繁体   English   中英

如何右键点击获取Div ID

[英]How to get Div Id on right click on it

我在页面中使用jquery的上下文菜单,但是单击此div上的右键时,无法获取特定div的ID。

$('#element').on("contextmenu",function(){
   alert(this.id);
}); 

要么

$('#element').on('mousedown', function(e) {
    if (e.which === 3) {
        alert(e.target.id);        
    }
});
$("#id").click(function() { console.log($(this).attr("id")); })

在jQuery中,触发事件的对象始终是this。

这是一个例子。

HTML ::

<div id="buttondiv">
    <button type="button">Click Me!</button>
</div>​

jQuery代码:

$(document).ready(function(){
    $("button").on("mousedown", function(e){
       if(e.which == 3){
          var divId = $(this).parent().attr("id");
          console.log(divId);
       }
   })
});​

我假设您的意思是“右键单击div”

这将适用于页面上的任何<div>

//bind the event to the document, using the delegate of "div"
$(document).on('mousedown', 'div', function (e) {
    //check that the right mouse button was used
    if (e.which === 3) {
        //log the [id] attribute of the element that was right-clicked on
        console.log($(this).attr('id'));
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM