更改父级Div背景onclick表单多个Child Div li

时间:2017-07-27 20:52:19

标签: javascript

我正在尝试使用多个li实例创建一个父div背景img更改onclick w。每个li应该将背景更改为该状态的地图。我成功地为一个实例做了这个

这有效:                                   

        <ul>
            <li><div class="panel-heading" role="tab" id="stateNine">
                <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion3" href="#stateal" aria-expanded="false" aria-controls="stateal">Alabama | </h3></div>
                </li>
                <script>function changeBackground() {
                        event.currentTarget.className = ('bucketal');
                }</script>`

这个工作一次,它会触发每个按钮上的最后一个脚本实例,忽略前一个。背景更改但仅限于最后一个实例的背景。总共有9个不同的实例。 (显示3)

<div onclick="changeBackground(this)" class="bucket2"> 
        <div class="locations">
    <div class="panel-group" id="accordion3" role="tablist" aria-multiselectable="true">
        <div class="panel panel-default loc" style="background-color;none;">

        <ul>
            <li><div class="panel-heading" role="tab" id="stateNine">
                <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion3" href="#stateal" aria-expanded="false" aria-controls="stateal">Alabama | </h3></div>
                </li>
                <script>function changeBackground() {
                        event.currentTarget.className = ('bucketal');
                }</script>
            <li><div class="panel-heading" role="tab" id="stateEight">
                <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion3" href="#statefl" aria-expanded="false" aria-controls="statefl">Florida | </h3></div>
                <script>function changeBackground() {
                        event.currentTarget.className = ('bucketfl');
                }</script></li>
            <li><div class="panel-heading" role="tab" id="stateSeven">
                <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion3" href="#statega" aria-expanded="false" aria-controls="statega">Georgia | </h3></div>
                <script>function changeBackground() {
                        event.currentTarget.className = ('bucketga');
                }</script></li></li>

这里有很多好帖子,但我没有找到多个实例的答案。如果我错过了,我道歉。我感谢我可能没有遵循内联HTML / JS实例的最佳实践,并且对最佳/新解决方案持开放态度。

1 个答案:

答案 0 :(得分:0)

<div id="changeBackground">
    <button data-class="red">
    Red
    </button>
     <button data-class="blue">
    blue
    </button>
     <button data-class="green">
    green
    </button>
</div>

的js

var el = document.getElementById("changeBackground");
el.addEventListener("click", changeBackground);
function changeBackground(e) {
        e.currentTarget.className = e.target.getAttribute('data-class');
}

的CSS:

.red {
  background-color: red;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}

https://jsfiddle.net/ye7dy58y/