简体   繁体   English

单击C#MVC调用javascript函数

[英]C# MVC call javascript function on click

How to we call a function from an external JS file on click? 如何在点击时从外部JS文件调用函数?

JS file on /Content/js/pj_no.js /Content/js/pj_no.js上的JS文件

function alertMe(){
    alert("me");
}

C# C#

@Scripts.Render("~/Content/js/pj_no.js")
<input value="親コード新規登録" type="button" onclick="alertMe()" />

Assuming this is in the same file iin my csHTML it is working fine. 假设这是在我的csHTML中的同一个文件中它工作正常。 But when I put it on the external JS it is not calling anymore. 但是当我把它放在外部JS上时,它就不再调用了。

I know my JS is in the right directory as if i trigger an $(document).ready(function () {} it is calling the alert. But I need it to be on click event. 我知道我的JS在正确的目录中,好像我触发$(文件).ready(function(){}它正在调用警报。但我需要它在点击事件上。

Help please 请帮助

$(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");
  }
)});

You need to make it global to get called. 你需要让它全局化才能被调用。 Please declare it out side of document ready function. 请在文档就绪功能的一侧声明它。

$(document).ready(function (
  alert("me"); -- This is working,

)});
  // NOTE: Following will work 
  function alertMe(){ 
      alert("me");
  }

you can bundle it first in App_Start > BundleConfig.cs inside RegisterBundles 你可以在App_Start第一捆绑它>里面BundleConfig.cs RegisterBundles

bundles.Add(new ScriptBundle("~/bundles/pj_no").Include(
                        "~/Content/js/pj_no.js"));

then you can call it in your view : 然后你可以在你的视图中调用它:

@Scripts.Render("~/bundles/pj_no")
<input value="親コード新規登録" type="button" onclick="alertMe()" />

You just need to simply put the external js function in script folder. 您只需将外部js函数放在脚本文件夹中即可。 在此输入图像描述

Then simply call include it on view 然后只需在视图中调用include it

@Scripts.Render("~/Scripts/pj_no.js")

Then simply call the function on onclick 然后只需在onclick上调用该函数

<input value="親コード新規登録" type="button" onclick="alertMe()" />

在此输入图像描述

Try the following code, it will work 尝试以下代码,它将工作

window.alertMe = function(){ //can call this function
    alert("me");
}

Your code is not working because your function gets added to the local scope of $.ready function. 您的代码无效,因为您的函数被添加到$.ready函数的本地范围。 By using window.alertMe your function will be added to global scope even if it is inside the $.ready method 通过使用window.alertMe即使函数位于$.ready方法内,您的函数也将被添加到全局范围

It is working now with this way. 现在正以这种方式工作。

In MVC we rarely uses onclick event on input element, usually we use jQuery like this: 在MVC中我们很少在输入元素上使用onclick事件,通常我们使用这样的jQuery:

$("#elementname").click(function () {
 alertMe(); 
});
<input value="親コード新規登録" type="button" id="elementname" />. 

– Tetsuya Yamamoto - 山本哲也

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM