2009-02-19 69 views
0

在jQuery中,我怎么才能找出哪个对象被点击?如何找出点击的内容?

有没有办法提醒(...)的标签类型?如果它是<a href><img>等?

+0

看起来像被过滤掉你的样本HTML标签。他们只是随机的例子,还是他们有重要的东西? – user64075 2009-02-19 06:19:43

回答

0

能否广告的onclick事件提醒属性

<p id='pWoo' onclick='alert(this.id);'>Woo</p> 

并非专用的jQuery。

+0

实际上,您可能不应该在您的HTML中嵌入JavaScript ...您最好使用Unobtrusive JavaScript方法(http://en.wikipedia.org/wiki/Unobtrusive_JavaScript)。 – cdmckay 2009-02-19 06:39:04

3

被点击的对象作为this传递到点击处理程序。你可以用nodeName找出元素的类型。就像这样:

function handle_click() { 
    var clicked_element = this; 
    alert(clicked_element.nodeName); 
} 
$("#mylink").click(handle_click); 
2

Magnar's answer是正确的,只要你想知道什么类型的元素的处理事件(你什么附加的事件)。如果您想确切知道单击哪个元素(包括元素的子元素),则需要event.target属性。使用Magnar的例子:

// show the type of the element that event handler was bound to 
function handle_click() { 
    var clicked_element = this; 
    alert(clicked_element.nodeName); 
} 

// show the type of the exact element that was clicked, which may be a child 
// of the bound element 
function handle_child_click(e) { 
    var clicked_element = e.target; 
    alert(clicked_element.nodeName); 
} 

// show the type of the element that matches "#myLink" 
$("#mylink").click(handle_click); 

// show the type of the element that matches "#myLink" or any of its children 
$("#mylink").click(handle_child_click);