2017-07-27 74 views
0

我想讓父div背景img更改onclick wwith多個li實例。每個李應該改變背景爲該狀態的地圖。我成功地做這一個實例更改父Div背景onclick表單多個子div 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實例的最佳實踐,並接受最佳/新的解決方案。

回答

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/

+0

這很適合!謝謝。作爲後續,當點擊除活動鏈接以外的任何地方時,我是否可以阻止背景變得空白。防爆。頁 - http://lectric.com/brockandscott/ – EBill

+0

我想通過擴展數據類到所有其他清除背景的div來解決這個問題。謝謝! – EBill