简体   繁体   中英

Get ID of clicked on element in function

I want to get the ID of an element I click on. I put the function in the onclick element, like this:

<a id="myid" class="first active" onclick="markActiveLink();" href="#home">Home</a>

And this is in the function:

function markActiveLink() {   
    alert($(this).attr("id"));
}

This doesn't work, as it says it isn't defined. Does it really forget about the ID, do I have to type it in the onclick?

Try: onclick="markActiveLink(this);" and

function markActiveLink(el) {   
    alert($(el).attr("id"));
}

why using an inline handler? Move to unobtrusive js

$(document).ready(function(){
  $('#myid').bind('click', function(){
     alert($(this).attr('id'));
  });
});

You have to pass the element to the function. JS itself isn't smarter than you :)

html:

<a id="myid" class="first active" onclick="markActiveLink(this);" href="#home">Home</a>

js:

function markActiveLink(e) {   
    alert(e.id);
}

Do not use $(this) because it does accidentally return the element you added the bind. When you click on an inner element, it also returns the outer element.

<div id="outer">
    <div id="inner">

    </div>
</div>

You better use the following appearance:

$("#outer").bind('click', function(e) {

    if(e.target.id === "inner")
    {
        alert("you clicked the inner element");
    }
    else
    {
        alert("you clicked the outer element");
    }
});

You can find a fiddle here: http://jsfiddle.net/vqab7jdo/1/

I try all the ways, spend almost 2 hours and finally found the best way I prefer try it:

< div onclick="div_Clicked()" id="some"/>

function div_Clicked(itemName) { alert(itemName); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM