我需要这个交互式元素,用户可以在其中切换各种按钮。某些按钮的值为4,其他按钮的值为1和0.当切换按钮的总和为ie时。 8,将显示文本。如果是4,则会显示另一个文本,等等。
任何人都可以帮助我使用下面的代码,因为我似乎无法让它发挥作用。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.selected {
color: red;
}
</style>
<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>
<br/><br/>
<div class="demo"><div>
<script>
var totalAmount = 0;
$(document).ready(function() {
$('.toggle').on('click', function() {
var value = $(this).val();
if($(this).hasClass('selected')) {
$(this).removeClass('selected');
totalAmount = parseInt(totalAmount) - parseInt(value);
}
else {
$(this).addClass('selected');
totalAmount = parseInt(totalAmount) + parseInt(value);
}
});
});
if (totalAmount >= 9 ) {
document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is higher or equal than 9"
};
else if (totalAmount < 9 && > 4) {
document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is higher than 4 and less than 9"
};
else if (totalAmount <= 4) {
document.getElementById("demo").innerHTML = "A text to be here if
totalAmount is less or equal to 4"
};
else {
document.getElementById("demo").innerHTML = "A text to be here if nothing
else is"
};
</script>
答案 0 :(得分:2)
else
阻止,即if(){}else{}
totalAmount < 9 && totalAmount > 4
而不是totalAmount < 9 && > 4
document.getElementById()
功能
var totalAmount = 0;
$(document).ready(function() {
$('.toggle').on('click', function() {
var value = $(this).val();
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
totalAmount = parseInt(totalAmount) - parseInt(value);
} else {
$(this).addClass('selected');
totalAmount = parseInt(totalAmount) + parseInt(value);
}
console.log(totalAmount)
if (totalAmount >= 9) {
document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher or equal than 9"
} else if (totalAmount < 9 && totalAmount > 4) {
document.getElementById("demo").innerHTML = "A text to be here if totalAmount is higher than 4 and less than 9"
} else if (totalAmount <= 4 && totalAmount > 1) {
document.getElementById("demo").innerHTML = "A text to be here if totalAmount is less or equal to 4"
} else {
document.getElementById("demo").innerHTML = "A text to be here if nothing else is"
};
});
});
&#13;
.selected {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toggle" value=4>Car</button>
<button class="toggle" value=4>House</button>
<button class="toggle" value=1>MC</button>
<button class="toggle" value=1>Moped</button>
<button class="toggle" value=0>Life</button>
<button class="toggle" value=0>Dog</button>
<br/><br/>
<div id="demo">
<div>
&#13;