我正在尝试编写一个简单的页面,其中每次点击都会使用getElementsByClassName更改网站上的定价。
这是有效的:
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
添加1年后不起作用():
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function 1year() {
var price2 = document.getElementsByClassName("price");
price2[0].innerHTML = "$8";
price2[1].innerHTML = "$16";
price2[2].innerHTML = "$24";
price2[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>
有谁知道为什么?
TIA。
答案 0 :(得分:3)
JavaScript中的函数或变量不能以数字开头。
标识符必须以美元符号($),下划线(_)或unicode字符开头。
在你的情况下,
<button onclick="1year()">1 year</button>
<button onclick="2year()">2 year</button>
<button onclick="3year()">3 year</button>
所有3个功能都无效。
答案 1 :(得分:0)
感谢@Richard Hamilton,这是完整的代码片段。
<script>
function monthly() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$10";
price[1].innerHTML = "$20";
price[2].innerHTML = "$30";
price[3].innerHTML = "$40";
}
function annually() {
var price = document.getElementsByClassName("price");
price[0].innerHTML = "$8";
price[1].innerHTML = "$16";
price[2].innerHTML = "$24";
price[3].innerHTML = "$32";
}
</script>
<button onclick="monthly()">Monthly</button>
<button onclick="annually()">1 year</button>
<br>
<span class="price">$1</span><br>
<span class="price">$2</span><br>
<span class="price">$3</span><br>
<span class="price">$4</span><br>