MVC查看在加载时运行的JavaScript函数

时间:2015-08-27 20:10:08

标签: javascript asp.net-mvc

我在MVC中有一个视图,它包含一个按钮,单击时应调用javascript函数。问题是加载视图时函数正在运行,而不是单击按钮时。

<label for="structureParameter">Choose a structure parameter</label><select id="structureParameter" name="structureParameter">
    <option disabled="disabled" selected="selected">...</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
<input type="button" id="submit" value="submit" />

<script type="text/javascript">
function setStructure() {
    var selectElement = document.getElementById("structureParameter");
    var pageType = selectElement.value
    return pageType;
}

$(document).ready(function () {
    $('#submit').onclick = setStructure();
})
</script>

函数setStructure()正在加载时运行,而不是在单击按钮时运行,因此尚未设置document.getElementById(&#34; structureParameter&#34;)。单击按钮后如何才能运行setStructure()?

我尝试移动$(&#39; #test&#39;)。onclick = setStructure();在document.ready之外,它没有帮助。

1 个答案:

答案 0 :(得分:2)

将事件处理程序更改为:

$(document).ready(function () {
    $('#submit').click(function () {
        alert('hello, world!');
    });
})

在您的情况下,请通过拨打alert

来替换setStructure()

小提琴:https://jsfiddle.net/mwatz122/ztc78z1e/