我正在尝试找出一个js脚本会在多个html页面上拉不同商品(Id)的价格(var)的地方,但是我正在使用的东西只有在所有var和与所有ID的顺序相同:
function similarfunction() {
var A1307 = 5.54;
document.getElementById('A1307').innerHTML = A1307;
var G2200 = 6.33;
document.getElementById('G2200').innerHTML = G2200;
var G5200 = 5.51;
document.getElementById('G5200').innerHTML = G5200;
var N3633 = 6.31;
document.getElementById('N3633').innerHTML = N3633;
var TS105 = 5.54;
document.getElementById('TS105').innerHTML = TS105;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test page</title>
</head>
<body onLoad="similarfunction()">
A1307 is $<span id="A1307"></span><br><br>
G2200 is $<span id="G2200"></span><br><br>
G5200 is $<span id="G5200"></span><br><br>
N3633 is $<span id="N3633"></span><br><br>
TS105 is $<span id="TS105"></span><br><br>
</body>
</html>
如果我将html页中的第一个ID更改为其他内容,其余的将无法正常工作...
我充其量只是个新手-只是试图找到一种方法来更新一个可以在整个ID范围内应用ID的js文档
感谢您的帮助。
答案 0 :(得分:0)
其余部分不起作用,因为没有带有您要搜索的ID的元素。 getElementById
失败,其余代码未执行,这是经典的runtime exception
。
还要更改变量的名称,因为这些变量和相应的元素ID之间可能存在冲突。用于现代浏览器的textContent
属性,而不是innerHTML
。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test page</title>
<script type="text/javascript">
function similarfunction(){
var price_A1307 = 5.54;
var span_A1307 = document.getElementById('A1307');
if (span_A1307) span_A1307.textContent = price_A1307;
var price_G2200 = 6.33;
var span_G2200 = document.getElementById('G2200');
if (span_G2200) span_G2200.textContent = price_G2200;
var price_G5200 = 5.51;
var span_G5200 = document.getElementById('G5200');
if (span_G5200) span_G5200.textContent = price_G5200;
var price_N3633 = 6.31;
var span_N3633 = document.getElementById('N3633');
if (span_N3633) span_N3633.textContent = price_N3633;
var price_TS105 = 5.54;
var span_TS105 = document.getElementById('TS105');
if (span_TS105) span_TS105.textContent = price_TS105;
}
</script>
</head>
<body onLoad="similarfunction()">
A1307 is $<span id="A1307"></span><br><br>
G2200 is $<span id="G2200"></span><br><br>
G5200 is $<span id="G5200"></span><br><br>
N3633 is $<span id="N3633"></span><br><br>
TS105 is $<span id="TS105"></span><br><br>
</body>
</html>