在“这个”父母中定位儿童

时间:2017-03-11 16:20:20

标签: javascript

假设我有两组div s - 都有点击按钮,点击后会改变该组中孩子的文字内容。

如何使用纯javascript实现这一目标?

提前致谢

HTML

<div class="parent">
  <button>Click</button>
  <div class="child">Test1</div>
  <div class="child">Test4</div>
</div>

<div class="parent">
  <button>Click</button>
  <div class="child">Test2</div>
  <div class="child">Test5</div>
</div>

的Javascript

var button = document.querySelectorAll("button");

for(i = 0; i < button.length; i++){
    button[i].addEventListener("click", function(){
        var parent = document.querySelectorAll(".parent");
        var child = parent.querySelector(".child:nth-child(2)");
        this.child.textContent = "success"; //just made up to show what I'm trying to accomplish
    });
}

2 个答案:

答案 0 :(得分:2)

假设您只想更改父级中的第一个div元素,这里有一种方法:

&#13;
&#13;
var button = document.getElementsByTagName("button");

Array.from(button).forEach(v => v.addEventListener('click', function() {
  this.parentNode.children[1].innerHTML = 'success';
}));
&#13;
<div class="parent">
  <button>Click</button>
  <div class="child">Test1</div>
  <div class="child">Test4</div>
</div>

<div class="parent">
  <button>Click</button>
  <div class="child">Test2</div>
  <div class="child">Test5</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

只需使用this关键字确定点击了哪个按钮,然后获取其.parentNode,然后获取其.children,选择第二个([1])并更改文字,如下:

var button = document.querySelectorAll("button");

for(i=0; i < button.length; i++) {
    button[i].addEventListener("click", function() {
        this.parentNode.children[1].innerHTML = 'success';
    });
}
<div class="parent">
  <button>Click</button>
  <div class="child">Test1</div>
  <div class="child">Test4</div>
</div>

<div class="parent">
  <button>Click</button>
  <div class="child">Test2</div>
  <div class="child">Test5</div>
</div>