javascript onclick获取div ID? [英] javascript onclick get the div id?

查看:177
本文介绍了javascript onclick获取div ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < div 

是否有可能在点击按钮时获得2个div标签的ID? ID = 主 >
< div id =content>
< / div>
< button onclick =function();>显示< /按钮>
< / div>

我在这里有2个div标签。第一个div在主div中,而content div在主div中,而按钮在主div中。



是否有可能获得<点击按钮时,2个div标签的id是否为 main content

当按下按钮时,预期输出:


  alert:main 
alert:content



解决方案

<你需要将元素传递给函数。然后,您可以使用 parentNode 来获取包含按钮的 DIV 。从那里,您可以使用 querySelector 来查找父级中的第一个 DIV



  function showIt(element){var parent = element.parentNode;警报(parent.id); var content = parent.querySelector(div); alert(content.id);}  

< div id = 主 > < div id =content> < / DIV> < button onclick =showIt(this);>显示它< / button>< / div>< div id =main2> < div id =content2> < / DIV> < button onclick =showIt(this);> show it< / button>< / div>< div id =main3> < div id =content3> < / DIV> < button onclick =showIt(this);>显示< / button>< / div>


Is it possible to get the ids of the 2 div tags on clicking the button, using javascript?

<div id="main">
<div id="content">
</div>
<button onclick="function();">show it</button>
</div>

I have 2 div tags here. The 1st div is in the main div while the content div is inside the main div and the button is inside the main div as well.

Is it possible to get the main and content id of the 2 div tags on clicking the button?

EXPECTED OUTPUT when I press the button:

alert: main
alert: content

解决方案

You need to pass the element to the function. Then you can use parentNode to get the DIV that contains the button. From there, you can use querySelector to find the first DIV in the parent.

function showIt(element) {
  var parent = element.parentNode;
  alert(parent.id);
  var content = parent.querySelector("div");
  alert(content.id);
}

<div id="main">
  <div id="content">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>
<div id="main2">
  <div id="content2">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>
<div id="main3">
  <div id="content3">
  </div>
  <button onclick="showIt(this);">show it</button>
</div>

这篇关于javascript onclick获取div ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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