Javascript 获取调用函数的元素的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7627161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID of element that called a function
提问by Ambo100
How can I get the ID of an element that called a JS function?
如何获取调用 JS 函数的元素的 ID?
body.jpgis an image of a dog as the user points his/her mouse around the screen at different parts of the body an enlarged image is shown. The ID of the area element is identical to the image filename minus the folder and extension.
body.jpg是狗的图像,因为用户将他/她的鼠标指向屏幕上身体的不同部位,会显示放大的图像。区域元素的 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>
I've done my research and have come to Stack Overflow as a last resort. I'm prefer a solution that doesn't involve jQuery.
我已经完成了我的研究,并将 Stack Overflow 作为最后的手段。我更喜欢不涉及 jQuery 的解决方案。
回答by James Sumners
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>
回答by jfriend00
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.
我很惊讶没有人提到this
在事件处理程序中的使用。它可以在现代浏览器中自动运行,也可以在其他浏览器中运行。如果您使用addEventListener
或attachEvent
安装您的事件处理程序,那么您可以使 的值this
自动分配给创建事件的对象。
Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.
此外,以编程方式安装的事件处理程序的用户允许您将 javascript 代码与 HTML 分开,这通常被认为是一件好事。
Here's how you would do that in your code in plain javascript:
以下是您将如何在纯 javascript 代码中执行此操作:
Remove the onmouseover="zoom()"
from your HTML and install the event handler in your javascript like this:
onmouseover="zoom()"
从您的 HTML 中删除并在您的 javascript 中安装事件处理程序,如下所示:
// 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);
回答by mixel
You can use 'this' in event handler:
您可以在事件处理程序中使用“this”:
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.
建议使用 attachEvent(IE < 9)/addEventListener(IE9 等浏览器)来附加事件。上面的例子是为了简洁起见。
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);
}
回答by Pointy
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 thinkit should give you the image tag, but that could be wrong.
然后this
在您的处理程序中将引用该元素。现在,我要提醒一下,我不能 100% 确定在<area>
标签中有处理程序时会发生什么,这主要是因为我已经<area>
有十年左右没有见过标签了。我认为它应该给你图像标签,但这可能是错误的。
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).
编辑- 是的,这是错误的 - 你得到的是<area>
标签,而不是<img>
. 因此,您必须获得该元素的父元素(地图),然后找到使用它的图像(即,<img>
其“usemap”属性指的是地图名称)。
edit again— except it doesn't matter because you wantthe area's "id" durr. Sorry for not reading correctly.
再次编辑- 除非这无关紧要,因为您想要该区域的“id”durr。抱歉没有正确阅读。
回答by Gregory Mostizky
I know you don't want a jQuery solution but including javascript inside HTML is a big no no.
我知道你不想要一个 jQuery 解决方案,但在 HTML 中包含 javascript 是一个很大的禁忌。
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).
我的意思是你可以这样做,但有很多原因你不应该这样做(如果你想要细节,请阅读不显眼的 javascript)。
So in the interest of other people who may see this question, here is the jQuery solution:
所以为了其他可能看到这个问题的人的兴趣,这里是 jQuery 解决方案:
$(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.
主要的好处是您不会将 javascript 代码与 HTML 混合在一起。此外,您只需编写一次,它将适用于所有标签,而不必为每个标签单独指定处理程序。
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.
额外的好处是每个 jQuery 处理程序都会接收一个包含大量有用数据的事件对象——例如事件的来源、事件的类型等等,这使得编写您所追求的代码类型变得更加容易。
Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.
最后,因为它是 jQuery,所以你不需要考虑跨浏览器的东西——一个主要的好处,尤其是在处理事件时。
回答by Fit Coder
i also want this to happen , so just pass the id of the element in the called function and used in my js file :
我也希望这种情况发生,所以只需在被调用函数中传递元素的 id 并在我的 js 文件中使用:
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";
}
回答by Roger
For others unexpectedly getting the Window element, a common pitfall:
对于其他人意外获得 Window 元素,一个常见的陷阱:
<a href="javascript:myfunction(this)">click here</a>
which actually scopes this
to the Window object. Instead:
它实际上作用this
于 Window 对象。反而:
<a href="javascript:nop()" onclick="myfunction(this)">click here</a>
passes the a
object as expected. (nop() is just any empty function.)
a
按预期传递对象。(nop() 只是任何空函数。)