简体   繁体   English

我需要将两个元素传递给onclick事件处理函数javascript而不仅仅是它们的id

[英]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.

相关问题 如何将触发 `onclick` 事件的元素的 id 传递给事件处理 function - How to pass the id of an element that triggers an `onclick` event to the event handling function 如何使用JAVASCRIPT在onclick事件中传递两个参数,例如id和title - How to pass two argument in onclick event like id and title with JAVASCRIPT 将onclick事件添加到javascript中新创建的表格标题中,但是onclick函数被添加到页面上的所有内容中,而不仅仅是我想要的一个 - Adding onclick event to newly created table header in javascript, but the onclick function is added to all th's on the page, not just the one I want javascript将函数传递给onclick事件 - javascript pass function to onclick event 通过Java onClick函数传递ID - Pass ID on onClick Function in Javascript 为什么我需要将匿名函数传递给onClick事件? - Why do I need to pass an anonymous function into the onClick event? Javascript:传递一个 onclick 事件调用 object 的 id - Javascript: Pass an onclick event the id of the calling object 我在onClick事件javascript函数中的ID有问题 - i have a problem with a id in onClick event javascript function 如何在JavaScript中将变量函数传递给onclick事件? - how to pass a variable function to an onclick event in javascript? 在 onclick 事件 Javascript 中通过引用传递 function - Pass function by reference in onclick event Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM