onclick并更改innerhtml

时间:2017-10-28 08:14:24

标签: onclick click innerhtml

我想点击我的按钮,当我点击每个按钮=> 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>

1 个答案:

答案 0 :(得分:0)

添加&#34; -10&#34;对于div的id

&#13;
&#13;
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;
&#13;
&#13;