我正在开发一个使用javascript更新文本的脚本,遗憾的是它因某些原因无法运行! 这是我正在使用的脚本:
<script type="text/javascript">
function update(data)
{
//Ali
var a;
if(document.getElementById("level").value = "5")
{
a = 0.1;
}
if(document.getElementById("level").value == "10")
{
a = 0.35;
}
var y;
var x = data.value;
y = a * x;
document.getElementById("pricep").innerHTML == "$"+y;
}
</script>
<select class="box-select" name="level" id="level">
<option value="5">Level 5</option>
<option value="10">Level 10</option>
</select>
<!-- a lot of code -->
<input type="number" required="" placeholder="Purchase Amount" max="250" min="1" name="amount" id="refamount" value="<?php echo $_POST['amount']?>" ONCHANGE="update(this)">
<span class="box-label" id="pricep">0 USD</span>
答案 0 :(得分:0)
两件事:
=
更改为==
。<select class="box-select" onchange="update(this)" name="level" id="level">
<option value="5">Level 5</option>
<option value="10">Level 10</option>
</select>
<!-- a lot of code --> <span class="box-label" id="pricep">0 USD</span>
<强> jsFiddle example 强>
答案 1 :(得分:0)
将onchange事件移动到select并将赋值运算符(=)更改为相等(==)。像:
<script type="text/javascript">
function update(data)
{
//Ali
var a;
if(data == "5")
{
a = 0.1;
}
if(data == "10")
{
a = 0.35;
}
var y;
var x = data.value;
y = a * x;
document.getElementById("pricep").innerHTML = "$"+y;
}
</script>
<select class="box-select" name="level" id="level" onchange="update(this.value)">
<option value="5">Level 5</option>
<option value="10">Level 10</option>
</select>
<!-- a lot of code -->
<span class="box-label" id="pricep" >0 USD</span>
答案 2 :(得分:0)
怎么样:
<select class="box-select" name="level" id="level">
<option value="5">Level 5</option>
<option value="10">Level 10</option>
</select>
<!-- a lot of code -->
<span class="box-label" id="pricep">0 USD</span>
和
var levelSelectBox = document.getElementById('level');
function updatePrice() {
var level = levelSelectBox.options[levelSelectBox.selectedIndex].value;
var factor = 0;
level= parseInt(level, 10); // turn it into an integer
if(level === 5) {
factor = 0.1;
} else if (level === 10) {
factor = 0.35;
}
var price = factor * level;
document.getElementById("pricep").innerHTML = "$" + price;
}
levelSelectBox.onchange = updatePrice;
进一步阅读:Comparison operators,document.getElementById,parseInt,HTMLSelectElement。
答案 3 :(得分:0)
我强烈建议您使用像jQuery这样的库。
<select class="box-select" name="level" id="level">
<option value="5">Level 5</option>
<option value="10">Level 10</option>
</select>
<!-- a lot of code -->
<span class="box-label" id="pricep">0 USD</span>
$(function () {
$('#level').bind('change', u);
function u(event)
{
select = event.target
console.log(select);
// select comes from 'this'
//Ali
var a;
if($(select).val() == "5")
{
a = 0.1;
}
if($(select).val() == "10")
{
a = 0.35;
}
console.log($(select).val());
var y;
var x = parseInt($(select).val());
y = a * x;
document.getElementById("pricep").innerHTML = "$"+y;
}
});