我想点击我的按钮,当我点击每个按钮=> p.innerhtml =点击该按钮的每个div。
<script>
var buttons = document.getElementsByClassName("b");
for(var i = 0; i < buttons.length ; i++) {
buttons[i].onclick = function (event) {
document.getElementById("name").innerHTML = document.getElementById(this.id).innerHTML
};
}
</script>
<div style="display: flex">
<div class="g" id="11">100</div>
<button id="1" class="b">btn</button>
</div>
<br>
<div style="display: flex;">
<div class="g" id="12">200</div>
<button id="2 " class="b">btn</button>
</div >
<br>
<div style="display: flex">
<div class="g" id="13">300</div>
<button id="3 " class="b">btn</button>
</div>
<p id="name"> name</p>
答案 0 :(得分:0)
添加&#34; -10&#34;对于div的id
var buttons = document.getElementsByClassName("b");
for(var i = 0; i < buttons.length ; i++) {
buttons[i].onclick = function (event) {
document.getElementById("name").innerHTML = document.getElementById(this.id-10).innerHTML
};
}
&#13;
<div style="display: flex">
<div class="g" id="1">100</div>
<button id="11" class="b">btn</button>
</div>
<br>
<div style="display: flex;">
<div class="g" id="2">200</div>
<button id="12 " class="b">btn</button>
</div>
<br>
<div style="display: flex">
<div class="g" id="3">300</div>
<button id="13 " class="b">btn</button>
</div>
<p id="name"> name</p>
&#13;