刚开始学习JavaScript;写一些具有相对基本功能的计算器。我发现需要在下拉菜单的选项标签中放置多个变量值,并且在研究之后我认为最简单的方法是将它们放在一个字符串中,然后用split()
函数拆分它们,但无论如何我指定的分隔符,它就像没有分隔符一样,并且单独分割每个字符。为什么呢?
<select name="fuel" onChange="document.scalc.fuel.value=document.scalc.fuel.value.split(',')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
</select>
答案 0 :(得分:0)
我无法让你的示例代码完全做任何事情 - 或许你已经将它缩短了一点。
您的页面可能看起来像
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Example</title>
<script>
/* TODO: Give this function a meaningful name. */
function x(srcId, targetId) {
// Get reference to the source element
var src = document.getElementById(srcId);
// Make sure it is a select element
if (src.nodeName.toLowerCase() === "select") {
var target = document.getElementById(targetId);
// Put the first part of the source's value in the target
target.value = src.value.split(",")[0];
}
}
</script>
</head>
<body>
<form id="scalc">
<select id="fuel" onChange="x('fuel', 'result')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
<option value="50x2,60">cu/ft Natural Gas(Via Super Burner, 70% Efficient)</option>
</select>
<input id="result" type="text" readonly="readonly" />
</form>
</body>
</html>
参考文献:
<meta charset='utf-8'> vs <meta http-equiv='Content-Type'>
Best Practice: Access form elements by HTML id or name attribute?
How can javascript determine the type of an html element?
同样有用:W3C Markup Validation Service