简体   繁体   English

从子div onclick获取div内容

[英]Get div content from a child div onclick

I have a wrapper div1, with div2 inside which contains a string. 我有一个包装div1,其中div2包含一个字符串。 When i click on div1 i want the content from div2 to appear in alert(); 当我单击div1时,我希望div2中的内容出现在alert()中; how can this be done ? 如何才能做到这一点 ?

document.getElementById(feats).addEventListener("click",function show() {
            var htmlstring = this.innerHTML;

            alert(htmlstring);

The code above simply just add an even listener and alert all the html code from the wrapper. 上面的代码只需添加一个均匀的侦听器,并警告包装程序中的所有html代码。

Thanks 谢谢

With jQuery , which is well worth learning: 使用jQuery ,值得学习:

$('#div1').click(function() {
    alert($('#div2').text());
});

This does what you want: 这就是您想要的:

<html>
<head></head>
<body>

<div id="div1" onclick="doAlert();" style="cursor: pointer; cursor: hand;">
<div id="div2">
  Hello, this is the contents of div2
</div>
</div>

<script type="text/javascript">
  function doAlert() {
    alert(document.getElementById("div2").innerHTML);
  }
</script>

</body>
</html>

Also, gentle nudge, you will get more responses if you start accepting answers. 另外,轻柔地推动,如果您开始接受答案,您将获得更多的答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM