![](/img/trans.png)
[英]How to call both javascript function and C# function on a single button click in MVC
[英]C# MVC call javascript function on click
如何在点击时从外部JS文件调用函数?
/Content/js/pj_no.js上的JS文件
function alertMe(){
alert("me");
}
C#
@Scripts.Render("~/Content/js/pj_no.js")
<input value="親コード新規登録" type="button" onclick="alertMe()" />
假设这是在我的csHTML中的同一个文件中它工作正常。 但是当我把它放在外部JS上时,它就不再调用了。
我知道我的JS在正确的目录中,好像我触发$(文件).ready(function(){}它正在调用警报。但我需要它在点击事件上。
请帮助
$(document).ready(function (
alert("me"); -- This is working,
function alertMe(){ //cant call this function
alert("me");
}
)});
$(document).ready(function (
alert("me"); -- This is working,
// NOTE: Following becomes local function. and will not work
function alertMe(){ //cant call this function
alert("me");
}
)});
你需要让它全局化才能被调用。 请在文档就绪功能的一侧声明它。
$(document).ready(function (
alert("me"); -- This is working,
)});
// NOTE: Following will work
function alertMe(){
alert("me");
}
你可以在App_Start第一捆绑它>里面BundleConfig.cs RegisterBundles
bundles.Add(new ScriptBundle("~/bundles/pj_no").Include(
"~/Content/js/pj_no.js"));
然后你可以在你的视图中调用它:
@Scripts.Render("~/bundles/pj_no")
<input value="親コード新規登録" type="button" onclick="alertMe()" />
尝试以下代码,它将工作
window.alertMe = function(){ //can call this function
alert("me");
}
您的代码无效,因为您的函数被添加到$.ready
函数的本地范围。 通过使用window.alertMe
即使函数位于$.ready
方法内,您的函数也将被添加到全局范围
现在正以这种方式工作。
在MVC中我们很少在输入元素上使用onclick事件,通常我们使用这样的jQuery:
$("#elementname").click(function () {
alertMe();
});
<input value="親コード新規登録" type="button" id="elementname" />.
- 山本哲也
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.