【问题标题】:get the id attribute from the paragraph which has been right-clicked从已被右键单击的段落中获取 id 属性
【发布时间】:2013-10-22 03:05:37
【问题描述】:

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

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

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

更新:

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

然后为 p 编写 mousedown 处理程序

$('p').on('mousedown', function(e){
    if(e.which== 3){
        alert(this.id)
    }
})

演示:Fiddle

【讨论】:

  • @RajeshPaul 为什么不使用getElementsByTagName 获取所有p 元素,然后将onmousedown 处理程序注册到它
  • 我应该在哪里做???如果你在你的回答中表现出来,我将被优先考虑。
  • @ArunPJohny 非常感谢。
【解决方案2】:

这里是函数:

 $('#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/

【讨论】:

    【解决方案3】:

    纯 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 2012-08-06
      相关资源
      最近更新 更多