从右键单击的段落中获取id属性

时间:2013-10-22 03:05:37

标签: javascript jquery

假设我有一个带有此html标记的文本:

<p id="myId">Some text <span>some other text</span></p>

当我右键点击段落的任何位置时,如何获取id的值?

更新

我只是将值传递给函数,我没有提及,以免使其复杂化。

3 个答案:

答案 0 :(得分:4)

p然后

编写一个mousedown处理程序
$('p').on('mousedown', function(e){
    if(e.which== 3){
        alert(this.id)
    }
})

演示:Fiddle

答案 1 :(得分:1)

这是功能:

 $('#myId').on('mousedown',function(event) {
if(event.which == 3){
    var i = $(this).attr('id');
    alert(i);
}

});

event.which()根据点击的按钮报告1,2或3。 阅读此处模式详细信息http://api.jquery.com/event.which/

答案 2 :(得分:0)

纯JavaScript版本:

var myp = document.getElementsByTagName("p");
for(var i =0;i < myp.length;i++){
  myp[i].addEventListener("mousedown",function(e){
     if(e.which == 3){
     console.log(this.id);
     }
  },false);
}
相关问题