获取调用函数的元素的 ID

如何获得调用 JS 函数的元素的 ID?

Jpg 是一个狗的图像,当用户将鼠标在屏幕上指向身体的不同部位时,放大的图像就会显示出来。Area 元素的 ID 与减去文件夹和扩展名的图像文件名相同。

<div>
<img src="images/body.jpg" usemap="#anatomy"/>
</div>


<map name="anatomy">
<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom()"/>
</map>


<script type="text/javascript">
function zoom()
{
document.getElementById("preview").src="images/nose.jpg";
}
</script>


<div>
<img id="preview"/>
</div>

我已经做了调查,作为最后的手段,我来到 Stack Overflow。我更喜欢不涉及 jQuery 的解决方案。

185290 次浏览

Pass a reference to the element into the function when it is called:

<area id="nose" onmouseover="zoom(this);" />


<script>
function zoom(ele) {
var id = ele.id;


console.log('area element id = ' + id);
}
</script>

You can code the handler setup like this:

<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/>

Then this in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area> tag, largely because I haven't seen an <area> tag in like a decade or so. I think it should give you the image tag, but that could be wrong.

edit — yes, it's wrong - you get the <area> tag, not the <img>. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img> whose "usemap" attribute refers to the map's name).

edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly.

I know you don't want a jQuery solution but including javascript inside HTML is a big no no.

I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).

So in the interest of other people who may see this question, here is the jQuery solution:

$(document).ready(function() {
$('area').mouseover(function(event) {
$('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
});
});

The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.

Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.

Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.

I'm surprised that nobody has mentioned the use of this in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener or attachEvent to install your event handler, then you can make the value of this automatically be assigned to the object the created the event.

Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.

Here's how you would do that in your code in plain javascript:

Remove the onmouseover="zoom()" from your HTML and install the event handler in your javascript like this:

// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}


function zoom() {
// you can use "this" here to refer to the object that caused the event
// this here will refer to the calling object (which in this case is the <map>)
console.log(this.id);
document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}


// register your event handler
setEventHandler("nose", "mouseover", zoom);

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
alert(evt.target.id);
}


var el = document.getElementById("preview");
if (el.addEventListener){
el.addEventListener('click', myHandler, false);
} else if (el.attachEvent){
el.attachEvent('onclick', myHandler);
}

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

For others unexpectedly getting the Window element, a common pitfall:

<a href="javascript:myfunction(this)">click here</a>

which actually scopes this to the Window object. Instead:

<a href="javascript:nop()" onclick="myfunction(this)">click here</a>

passes the a object as expected. (nop() is just any empty function.)

If you setup a listener like this:

buttons = document.getElementsByClassName("btn-group")
for(let i=0;i<buttons.length;i++){
buttons[i].addEventListener("click", (e) => { btnClicked(e);},false);
}

then you can get the id like this:

function btnClicked(e){
console.log(e.target.id)
}

First Way: Send trigger element using this

<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>


<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element


alert(clicked_element.id + "Was clicked!!!");
}
</script>

This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.


Second Way: Send trigger element id using this.id

<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>


<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)


alert(clicked_id + "Was clicked!!!");
}
</script>

This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.

You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.

Let's say, you have a button like this:

<button id="btn1" onclick="doSomething()">Do something</button>

In the function, you can reach the id with this way:

function doSomething() {
let callerElementId = event.srcElement.id;
console.log(callerElementId);
}