将字符串文字从html传递给javascript函数

时间:2012-11-11 18:15:55

标签: javascript html escaping literals

在IE9中我收到错误Microsoft JScript运行时错误:'populatedropdown'在行<input type="button"....上未定义

我假设我没有正确地转义文字值。我该怎么改变?

<html>
<head>
<title>Add items to dropdown</title>

<script type="text/javascript">
function populatedropdown(var devicelist) {
    var devList = document.frm.optdevices;
    var arrDev = split(devicelist, ";");

     devList.options.length = 0; // this removes existing options

     for (var i = 0; i <= 3; i++) {
         var option = new Option(arrDev[i],i);
         devList.options[i] = option; 
     }
}

</script>

</head>
<body>
<form name="frm">

<select name="optdevices">
</select>

<input type="button" value="TestAdd" onclick="populatedropdown('201;202;203;')" />

</form>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

将JavaScript与HTML分开并删除语法错误。见fiddle

function populatedropdown(devicelist) {
    var devList = document.frm.optdevices;
    var arrDev = devicelist.split(';'); // split not defined

     devList.options.length = 0; // this removes existing options

     for (var i = 0; i <= 3; i++) {
         var option = new Option(arrDev[i],i);
         devList.options[i] = option; 
     }
}

// on window load
window.addEventListener('load', function load(){
    // attach event listener to button
    document.getElementById('testID').addEventListener('click', function click(){
        populatedropdown('201;202;203;');
    }, false);
}, false);
​

HTML

<form name="frm">

<select name="optdevices">
</select>

<input id="testID" type="button" value="TestAdd" />

</form>​

答案 1 :(得分:0)

由于函数参数中包含var,因此您的函数无效。只要脚本中出现语法错误,就无法识别该函数。 function populatedropdown(var devicelist)无效。参数

中不应有var
function populatedropdown(devicelist) {
    var devList = document.frm.optdevices;
    var arrDev = split(devicelist, ";");

     devList.options.length = 0; // this removes existing options

     for (var i = 0; i <= 3; i++) {
         var option = new Option(arrDev[i],i);
         devList.options[i] = option; 
     }
}

答案 2 :(得分:0)

首先,你不应该通过定义函数来编写var,而第二次使用函数split是错误的,应该使用split var result = strToSplit.split(";"),如果您希望按;拆分,可以在此处阅读有关拆分的信息Javascript Split method

这是工作片段

function populatedropdown(devicelist) {
    var devList = document.frm.optdevices;
    var arrDev = devicelist.split(";");

     devList.options.length = 0; // this removes existing options

     for (var i = 0; i <= 3; i++) {
         var option = new Option(arrDev[i],i);
         devList.options[i] = option; 
     }
}

刚刚在IE9上测试