在纯JS中获取clicked元素的parentNode [英] get parentNode of clicked element in plain JS
问题描述
我需要获取纯JS(没有jQuery或其他框架)中被单击元素的parentNode.我目前正在使用 document.getElementById("item_click")
但我想将 id ="item_click"
更改为 class ="item_click"
,以便可以使用多个框.我只是不知道如何将 this
集成到脚本中
I need to get the parentNode of a clicked element in plain JS (no jQuery or other frameworks)
I am currently using document.getElementById("item_click")
but I want to change id="item_click"
to class="item_click"
so I can use multiple boxes.
I just don't know how to integrate this
in the script
这是一个小提琴<<<玩
Here's a Fiddle <<< play with it
HTML
<div class="item">
<div class="item-tester" >
<div class="item-icon"></div>
<div class="item-title">Item Title</div>
</div>
<div id="item_click" onmousedown="new_class(event)" onmouseup="revert_class(event)" onmouseout="revert_class(event)"></div>
</div>
JS
function new_class(event) {
wClick = document.getElementById("item_click");
wTile = wClick.parentNode;
wTile.className = wTile.className + " added-class";
}
function revert_class(event) {
wTile.className = "item";
}
我要更改
wClick = document.getElementById("item_click");
wTile = wClick.parentNode;
类似
wClick = this;
wTile = wClick.parentNode;
我知道如何在jQuery中执行此操作,但由于 this
将是 window
(我认为)
I know how to do this in jQuery but it will not work in plain JS as this
would be the window
(I think)
顺便说一句.我需要(事件),因为这只是我正在使用的整个代码的一部分.
推荐答案
function new_class(event) {
wTile = event.target.parentNode;
wTile.className = wTile.className + " added-class";
}
这篇关于在纯JS中获取clicked元素的parentNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!