简体   繁体   中英

C# MVC call javascript function on click

How to we call a function from an external JS file on click?

JS file on /Content/js/pj_no.js

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

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. But when I put it on the external JS it is not calling anymore.

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.

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

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. 在此输入图像描述

Then simply call include it on view

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

Then simply call the function on 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. By using window.alertMe your function will be added to global scope even if it is inside the $.ready method

It is working now with this way.

In MVC we rarely uses onclick event on input element, usually we use jQuery like this:

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

– Tetsuya Yamamoto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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