我正在尝试根据选择将数据的值切换为动物或植物,并且我想将动物数组保持为默认。我的代码无法正常工作,并且有一种方法可以安全地执行此操作,而不会过多地破坏全局空间
let animal = ['cat','dog','lion'];
let plant =['Orange','Mango','banana'];
//-----//defult----
data = animal;
let toolTipsMsg ='Animal distribution';
//-----//defult----
let anima = document.querySelector('#animalBtn');
let plan = document.querySelector('#plantBtn');
function fnAnimal(){
if(data !== animal){
window.data = animal;
window.toolTipMsg ='Animal distribution';
}
}
function fnPlant(){
if(data !== plant){
window.data = plant;
window.toolTipMsg ='Plant distribution';
}
}
anima.addEventListener('click', fnAnimal, false);
plan.addEventListener('click', fnPlant, false);
document.getElementById('show').innerHTML = data.toString();
<!--//button-->
<div class="btn-group btn-group-toggle">
<label class="btn btn-outline-primary" >
<input type="radio" name="source" id="animalBtn" autocomplete="off"> Animal
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="source" id="plantBtn" autocomplete="off" > Plant
</label>
</div>
<p id='show'> </p>
<!--//button-->
无需进行太多更改,以下代码通过在每个事件处理程序内添加#show
来更改document.getElementById('show').innerHTML = data.toString();
中的值。
let animal = ['cat','dog','lion'];
let plant =['Orange','Mango','banana'];
//-----//defult----
data = animal;
let toolTipsMsg ='Animal distribution';
//-----//defult----
let anima = document.querySelector('#animalBtn');
let plan = document.querySelector('#plantBtn');
function fnAnimal(){
if(data !== animal){
window.data = animal;
window.toolTipMsg ='Animal distribution';
}
document.getElementById('show').innerHTML = data.toString();
}
function fnPlant(){
if(data !== plant){
window.data = plant;
window.toolTipMsg ='Plant distribution';
}
document.getElementById('show').innerHTML = data.toString();
}
anima.addEventListener('click', fnAnimal, false);
plan.addEventListener('click', fnPlant, false);
<!--//button-->
<div class="btn-group btn-group-toggle">
<label class="btn btn-outline-primary" >
<input type="radio" name="source" id="animalBtn" autocomplete="off"> Animal
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="source" id="plantBtn" autocomplete="off" > Plant
</label>
</div>
<p id='show'> </p>
<!--//button-->