在 MVC 视图上使用 javascript 和 C# 为动态创建的元素创建 onclick 方法

Create onclick method for dynamically created element using javascript and C# on MVC View

我面临的问题是,当 运行 这段代码工作正常,直到我在脚本 #option.onclick(vise()); 之间添加这行代码。我正在尝试做的工作是在单击时创建选项或选择任何选项时我想调用该函数但是当添加此行时整个事情都停止工作。

<html>
<head><head>
<body>

<script type="text/javascript">

var jScriptArray=[];

@{
    for(int i = 0; i < ViewBag.userClass.Count; i++)
    {
        <text>jScriptArray[@i] = "@ViewBag.userClass[@i].username";</text>
    }
}
var select = document.getElementById("global");

for (var i = 0; i < jScriptArray.length; i++)
{
    var option = document.createElement("OPTION"),            
        txt = document.createTextNode(jScriptArray[i]);
    option.appendChild(txt);
    option.onclick(vise()); #Error Generator
    option.setAttribute("value", jScriptArray[i]);
    select.insertBefore(option, select.lastChild);
}

function vise() {
    console.log("hello world.");
}

</script>

<form action="DeleteUser" method="post" class="form-horizontal">
                    
                    <div class="control-group">
                        <label class="control-label">Username :</label>
                        <div class="controls">
                            <select id="global" name="username">
                                <option value="default">Select</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-actions">
                        <button type="submit" class="btn btn-success">Save</button>
                    </div>
                </form>


</body>
</html>

更改为 select.addEventListener("change", vise) - 不管 onclick=(vice()) 是错误的语法 - 你可以 onclick=vice; 但 addEventListener 是推荐的方法

这里有一个更优雅的方法

const select = document.getElementById("global");
select.addEventListener("change",vice)
select.innerHTML = jScriptArray
  .map(item => (`<option value="${item}">${item}</option>`)).join("")