获取单击的元素父节点的数组编号

Get the array number of a clicked elements parent node

本文关键字:数组 编号 父节点 元素 单击 获取      更新时间:2023-09-26

我需要能够点击按钮并返回其父数组编号,这样我就可以只将样式应用于具有相同类名的众多div中的一个,如果可能的话,我希望用普通javascript来实现这一点。

    <div class="contentBox">
            <button onclick="expand()" class="contentBoxButton"> + </button>
            <title>Lorem Ipsum Here</title>
            <p> 
                Lorem Ipsum HereLorem Ipsum HereLorem Ipsum HereLorem Ipsum HereLorem Ipsum 
            </p>
        </div>
       <script>
         function expand(){
            var button = document.getElementsByClassName('contentBoxButton');
            var parent = button.parentNode;
            parent.style.height = '200px';
        }
       </script>

感谢Felix Kling对.parentNode 的评论

你没有得到一个单独的元素的原因是,你一开始是通过它的类访问点击的按钮
var button = document.getElementsByClassName('contentBoxButton');
..,这确实会为您提供该类的所有元素的节点列表
因此,在那之后的一行中对parentNode的调用要么不起作用,要么结果是所有父节点的另一个列表。。


这就是你需要让它工作:

小提琴:http://jsfiddle.net/13pkrabq/3/


HTML

<div class="contentBox">
    <button onclick="expand(this)"> + </button>
    <p>
        Text Text Text 
    </p>
</div>

JS

function expand(btn) {
    btn.parentNode.style.height = "200px";
}

CSS

.contentBox {
    background-color:#777777;
}

(我添加了CSS以使contextBox可见)

如果它是您想要扩展的div,请考虑将监听器放在上面,这样您就不必去寻找了。使用this传递对div的引用,然后使用按钮值打开或关闭div。

同时在"+"answers"-"之间切换按钮的值,并使用类应用CSS:

<div onclick="expand(this)">
  <input type="button" value="+" class="expandContentButton">
  <span class="title">Foo bar</span>
  <p class="contentPara">here is the content</p>
</div>
<script>
  function expand(el) {
    var cb = el.querySelectorAll('.expandContentButton')[0];
    if (cb == event.target || cb == event.srcElement) {
      el.className = cb.value == '+' ? 'open' : 'closed';
      cb.value = cb.value == '+' ? '-' : '+';
    }
  }
</script>

以及一些CSS:

<style type="text/css">
  .title {
    font-weight: bold;
    font-size: 150%;
  }
  .open {}
  .closed {
    height: 30px;
    overflow: hidden;
  }
  .expandContentButton {
    text-align: middle;
    width: 3em;
  }
</style>