[英]MVC View JavaScript Function Running at Load Time
I have a view in MVC and it contains a button that should call a javascript function when clicked. 我在MVC中有一个视图,它包含一个按钮,当单击该按钮时应调用javascript函数。 The problem is the function is running when the view is loaded instead of when the button is clicked. 问题在于,当加载视图而不是单击按钮时,该函数正在运行。
<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>
The function setStructure() is being run at load instead of when the button is clicked, so document.getElementById("structureParameter") is not yet set. setStructure()函数是在加载时而不是在单击按钮时运行的,因此尚未设置document.getElementById(“ structureParameter”)。 How can only run setStructure() once the button is clicked? 单击按钮后,如何才能仅运行setStructure()?
I tried moving $('#test').onclick = setStructure(); 我试图移动$('#test')。onclick = setStructure(); outside of document.ready and it doesn't help. 在document.ready之外,并且没有帮助。
Change the event handler to look like this: 将事件处理程序更改为如下所示:
$(document).ready(function () {
$('#submit').click(function () {
alert('hello, world!');
});
})
In your case, replace the alert
with a call to setStructure()
根据您的情况,将alert
替换为对setStructure()
的调用
Fiddle: https://jsfiddle.net/mwatz122/ztc78z1e/ 小提琴: https : //jsfiddle.net/mwatz122/ztc78z1e/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.