你能使用event.target定位元素父元素吗? [英] Can you target an elements parent element using event.target?

查看:951
本文介绍了你能使用event.target定位元素父元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的页面的innerHTML更改为我点击的元素的innerHTML,唯一的问题是我希望它采取整个元素,如:

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:

<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>

我用javascript编写的代码:

Whereas the code that i have written in javascript:

function selectedProduct(event){
  target = event.target;
  element = document.getElementById("test");
  element.innerHTML = target.innerHTML;
}

将定位我点击的特定元素。

will target the specific element that i click on.

我想要实现的是当我点击< section> 元素中的任何位置时,它将采用整个元素的innerHTML而不是特定的我点击过的一个。

What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.

我愿意sume它与选择被点击的那个的父元素有关,但我不确定,也无法在网上找到任何东西。

I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.

如果可能,我想要远离JQuery

If possible i would like to stay away from JQuery

推荐答案

我认为您需要的是使用 event.currentTarget 。这将包含实际具有事件侦听器的元素。因此,如果整个< section> 的eventlistener event.target 将是点击的元素,< section> 将在 event.currentTarget

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.

否则 parentNode 可能就是你要找的东西。

Otherwise parentNode might be what you're looking for.

link to currentTarget

link到parentNode

这篇关于你能使用event.target定位元素父元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆