【问题标题】:Create onclick method for dynamically created element using javascript and C# on MVC View在 MVC 视图上使用 javascript 和 C# 为动态创建的元素创建 onclick 方法
【发布时间】:2020-11-07 19:27:18
【问题描述】:

我面临的问题是,在运行此代码时,代码工作正常,直到我在脚本#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>

【问题讨论】:

    标签: javascript c# model-view-controller


    【解决方案1】:

    更改为 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("")
    

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 2012-07-14
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多