我正在尝试使用多个 li 实例在单击时更改父div 背景 img。每个 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>`
这只工作一次,它会在每个按钮上触发最后一个脚本实例,忽略前一个。背景会更改,但只会更改为最后一个实例的背景。总共将有 # 个不同的实例。(显示 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 实例的最佳实践,并且对最佳/新解决方案持开放态度。
<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/