【发布时间】:2013-10-22 03:05:37
【问题描述】:
假设我有一个带有这个 html 标记的文本:
<p id="myId">Some text <span>some other text</span></p>
当我右键单击段落的任意位置时,如何获取id 的值?
更新:
我只是将值传递给一个函数,我没有提及,以免复杂化。
【问题讨论】:
标签: javascript jquery
假设我有一个带有这个 html 标记的文本:
<p id="myId">Some text <span>some other text</span></p>
当我右键单击段落的任意位置时,如何获取id 的值?
更新:
我只是将值传递给一个函数,我没有提及,以免复杂化。
【问题讨论】:
标签: javascript jquery
然后为 p 编写 mousedown 处理程序
$('p').on('mousedown', function(e){
if(e.which== 3){
alert(this.id)
}
})
演示:Fiddle
【讨论】:
getElementsByTagName 获取所有p 元素,然后将onmousedown 处理程序注册到它
这里是函数:
$('#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/
【讨论】:
纯 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);
}
【讨论】: