最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check which html element triggers onclick - Stack Overflow

programmeradmin2浏览0评论

I have html like below:

<div onclick=" callJavascript()">

<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>

</div>

When I click 'abc' or 'ghi', is there anywhere inside function callJavascript(), to find out which span id I clicked on ?

I have html like below:

<div onclick=" callJavascript()">

<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>

</div>

When I click 'abc' or 'ghi', is there anywhere inside function callJavascript(), to find out which span id I clicked on ?

Share Improve this question edited Jun 24, 2011 at 18:20 Luc125 5,85735 silver badges35 bronze badges asked Jun 24, 2011 at 13:18 comettacometta 35.7k84 gold badges220 silver badges329 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 9

Yes there is :

For Not IE browsers :

function callJavascript ( e ) {

    alert(e.target); // the DOMElement object
    alert(e.target.id); // the object's id

}

For IE :

function callJavascript ( e ) {

    alert(e.srcElement); // the DOMElement object
    alert(e.srcElement.id); // the object's id

}

You must nevertheless adapt your html :

<div onclick=" callJavascript(e)"> // replace "e" by "event" in IE.

<span id="abc"> abc </span>
<span id="def"> def </span>
<span id="ghi"> ghi </span>

</div>

If you want a more complete reference, here it is : http://www.quirksmode.org/js/events_properties.html

Wow ! May I mention, for better accuracy, your event listener should not be on the div element, instead, it may be triggered by the span elements themselves. The target or srcElement being the one on which the event occurs.

It's not part of the question, but it's worth saying : I usually prefer to avoid event attachment in html code since it causes scope problems and forces you, as in your case, to manually pass the event parameter.

You have to add the event param to your onclick listener to have the event accessible within your listener.

<div onclick="callJavascript(event)">

Then use the target or srcElement property to get the DOM element.

function callJavascript(e) {
    var target = e.srcElement || e.target;
    alert(target.id);
}

Working demo

You could use jquery as follows:

$(function() {
    $("span").click(function(e) {
        alert(this.id);
    }
});

See it in action here: http://jsfiddle.net/3KfyG/.

for get attributes or class:

<div class="foo" my_attr="foo2" onclick="callJavascript(event)">
function callJavascript(e) {
    var target = e.srcElement || e.target;    
    console.log(target.className);
    console.log(target.getAttribute('foo2'));
}

Look this link: http://krook.org/jsdom/HTMLParagraphElement.html

Try:

<script>
    function callJavascript() {
        alert(event.target.id);
    } 
</script>
发布评论

评论列表(0)

  1. 暂无评论