获取调用函数的元素的 ID

发布于 2024-12-07 19:14:11 字数 604 浏览 0 评论 0原文

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

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>

我已经完成了研究,并把 Stack Overflow 作为最后的手段。我更喜欢不涉及 jQuery 的解决方案。

How can I get the ID of an element that called a JS function?

body.jpg is 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.

<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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

掌心的温暖 2024-12-14 19:14:12

对于其他意外获取 Window 元素的人来说,这是一个常见的陷阱:

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

实际上将 this 范围限定为 Window 对象。相反:

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

按预期传递 a 对象。 (nop() 只是任何空函数。)

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.)

反目相谮 2024-12-14 19:14:12

如果你像这样设置一个侦听器:

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

那么你可以像这样获取 id:

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

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)
}
凯凯我们等你回来 2024-12-14 19:14:12

第一种方法:使用 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>

通过这种方式发送一个类型为:HTMLElement 的对象,您就可以获得元素本身。你不需要关心元素是否有 id 或任何其他属性。它本身就可以很好地工作。


第二种方式:使用 this.id 发送触发元素 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>

这种方式发送一个类型为:String的对象,并且您不会获得元素本身。所以在使用之前,你需要确保你的元素已经有一个id。

您不得自行发送元素 id,例如 onClick="myFun(btn02)"。这不是干净的代码,它会使您的代码失去功能。

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.

戈亓 2024-12-14 19:14:12

假设您有一个如下所示的按钮:

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

在该函数中,您可以通过以下方式访问 id:

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

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);
}
囍孤女 2024-12-14 19:14:11

调用函数时将对元素的引用传递给函数:

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

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

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

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>
不寐倦长更 2024-12-14 19:14:11

我很惊讶没有人提到在事件处理程序中使用 this 。它可以在现代浏览器中自动运行,并且可以在其他浏览器中运行。如果您使用addEventListenerattachEvent来安装事件处理程序,那么您可以将this的值自动分配给创建的对象事件。

此外,以编程方式安装的事件处理程序的用户允许您将 javascript 代码与 HTML 分开,这通常被认为是一件好事。

以下是在纯 javascript 代码中执行此操作的方法:

从 HTML 中删除 onmouseover="zoom()" 并在 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);

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);
滿滿的愛 2024-12-14 19:14:11

您可以在事件处理程序中使用“this”:

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

或者将事件对象传递给处理程序,如下所示:

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

建议使用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);
}

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);
}
分分钟 2024-12-14 19:14:11

您可以像这样编写处理程序设置:

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

然后处理程序中的 this 将引用该元素。现在,我要提出警告,我不能 100% 确定当您在

标记中有处理程序时会发生什么,很大程度上是因为我还没有看到

标签大约十年左右。我认为它应该为您提供图像标签,但这可能是错误的。

编辑 - 是的,这是错误的 - 你得到的是

标签,而不是 。因此,您必须获取该元素的父元素(地图),然后找到使用它的图像(即 ,其“usemap”属性引用地图的名称) 。

再次编辑 - 但这并不重要,因为您想要该区域的“id”durr。抱歉没有正确阅读。

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.

恰似旧人归 2024-12-14 19:14:11

我知道您不想要 jQuery 解决方案,但在 HTML 中包含 javascript 是一个很大的禁忌。

我的意思是你可以这样做,但有很多原因你不应该这样做(如果你想了解详细信息,请阅读不引人注目的 javascript)。

因此,为了其他可能看到这个问题的人的利益,这里是 jQuery 解决方案:

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

主要好处是您不会将 javascript 代码与 HTML 混合。此外,您只需要编写一次,它将适用于所有标签,而不必分别为每个标签指定处理程序。

额外的好处是每个 jQuery 处理程序都会接收一个包含许多有用数据的事件对象 - 例如事件源、事件类型等,从而使编写您想要的代码变得更加容易。

最后,由于它是 jQuery,因此您无需考虑跨浏览器的问题 - 这是一个主要优点,尤其是在处理事件时。

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.

旧时光的容颜 2024-12-14 19:14:11

我也希望这样的事情发生
所以只需在被调用函数中传递元素的 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";
}

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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文