[英]I need to pass two elements to an onclick event handling function javascript and not just their id's
Suppose I have 2 elements in my code and I want to pass their respective id's to an event handling function. 假设我的代码中有2个元素,我想将它们各自的id传递给事件处理函数。 (In my example below, I have a div and a button)
(在我下面的例子中,我有一个div和一个按钮)
<div id="div1">
<input type="button" id="button1" onclick="doSomething(this, [here comes id of div])" />
</div>
For the button, instead of writing the id which is "button1", I simply passed the element itself using the "this" keyword. 对于按钮,我只是使用“this”关键字传递元素本身而不是写入“button1”的id。 Now my question is, is there a way where I can pass the div element itself in the function and not just its id just like what I did with the button element?
现在我的问题是,有没有一种方法可以在函数中传递div元素本身,而不仅仅是像我使用button元素那样传递它的id?
Any help would be greatly appreciated. 任何帮助将不胜感激。
You can use the parentNode
property ; 您可以使用
parentNode
属性 ;
this.parentNode
As this returns a DOMElement
(similar to this
), you can access the ID the same via; 因为这会返回
DOMElement
(类似于this
),您可以访问相同的ID;
this.parentNode.id
... should you want to. ......你想要吗?
Just get it from the parent in the callback: 只需从回调中的父级获取它:
function clickHandler(e){
console.log(e.target.parentNode.id);
}
Why do you need to pass it in the first place? 为什么你需要首先传递它? Access the div via
parentNode
. 通过
parentNode
访问div。
onclick="doSomething(this);"
and 和
function doSomething(btn) {
var div = btn.parentNode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.