简体   繁体   English

为什么简单的MVC教程未调用我的javascript函数? 为什么我也不能调试?

[英]Why is my javascript function not being invoked for simple MVC tutorial? Why can't I debug either?

Problem 问题

I have been following this simple tutorial found here . 我一直在关注这里找到的这个简单教程。 However, I want to modify it so that the calculator is only invoked when the client clicks submit. 但是,我想对其进行修改,以便仅在客户端单击“提交”时才调用计算器。 However, when I click the submit button, no action is observed. 但是,当我单击“提交”按钮时,没有观察到动作。 I am not even seeing the alert. 我什至没有看到警报。

EDIT: 编辑:

I have modified the code per Ojay's suggestions. 我已经按照Ojay的建议修改了代码。 However, I am getting this error when I try to debug. 但是,尝试调试时出现此错误。 I am getting this exact issue except I have VS13 Update 3. Multiple things going on here? 除了VS13 Update 3,我得到了这个确切的问题 。这里发生了很多事情吗?

Code

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Sample Calculator</title>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">


        $(document).ready(function () {
            $('#my-calc').on('submit', function () {
                alert("This button is working?");
                calculate();
            });



           function calculate()
           {

               alert('hi');
               //Add 
               try {

                   $('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

               } catch (e) {

               }

               //Subtract
               try {

                   $('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));

               } catch (e) {

               }

               //Multiply
               try {

                   $('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));

               } catch (e) {

               }

               //Divide
               try {

                   $('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));

               } catch (e) {

               }
           }

        });



    </script>

</head>
<body>
    <div><h4>Sample Calculator</h4></div>
    @using (Html.BeginForm())
    {
        <p> @Html.Label("Input 1") : @Html.TextBox("num1","0")</p>
        <p> @Html.Label("Input 2") : @Html.TextBox("num2", "0")</p>
        <p> @Html.Label("Sum ") : @Html.TextBox("sum")</p>
        <p> @Html.Label("Sub ") : @Html.TextBox("sub")</p>
        <p> @Html.Label("Mult ") : @Html.TextBox("mul")</p>
        <p> @Html.Label("Div ") : @Html.TextBox("div")</p>
        <button id="my-calc" type="button">Calculate</button>


    }   
</body>
</html>

Attempts 尝试次数

  • Put in alert. 置于警报中。 Not observed. 没有观察到。
  • Rewrote it from documents.on.ready(). 从documents.on.ready()重写它。 See below. 见下文。
  • RTFM as seen here RTFM所看到这里
  • Searched stackoverflow. 搜索堆栈溢出。 Didn't find anything that worked. 找不到任何有效的方法。

Edit: I had something originally like the tutorial I was looking at. 编辑:我原来有一些东西就像我正在看的教程。 I had: 我有:

    $(document).ready(function(){

  $('#my-calc').on('submit', function (){ //stuff}


    }

I don't understand why my function is not being invoked? 我不明白为什么我的函数没有被调用? My form id is correct. 我的表格ID是正确的。 All I want to do is invoke this calculator method so my label's sum, sub, mult, and div display the results. 我要做的就是调用此计算器方法,以便我标签的sum,sub,mult和div显示结果。

Please pardon the simplistic nature of this question, but I feel it would be useful for others doing .NET MVC tutorials who might also be having this problem. 请原谅这个问题的简单性,但是我认为这对于其他从事.NET MVC教程的人也可能会遇到此问题很有用。 As a result of this question, I decided to obtain a book on jQuery. 由于这个问题,我决定购买一本有关jQuery的书。 Thanks for your assistance. 谢谢你的协助。

You're running your code before your form is rendered. 在呈现表单之前,您正在运行代码。 Therefore, $('.my-calc') is returning an empty object, and doing nothing. 因此, $('.my-calc')返回一个空对象,什么也不做。 Also, the selector for an item by ID is $('#my-calc') , your selector was looking for an element with class my-calc 另外,ID项的选择器是$('#my-calc') ,您的选择器正在寻找具有my-calc类的元素

// Passing a function into `$()` makes it run after the DOM is ready.
$(function() {
    $('#my-calc').on('submit', function (){
        alert("This button is working?");
        calculate();
    });
});

For ids in jquery, you have to use #my-calc 对于jquery中的ID,您必须使用#my-calc

But frankly, I think you're looking to call calculate on the button click otherwise you're going to have to submit your form every time you press the button, which kinda defeats the purpose of the javascript. 但是坦率地说,我想您希望在按钮单击时调用计算,否则每次单击按钮都必须提交表单,这有点违反了javascript的目的。

$("input").on("click", calculate);

http://jsfiddle.net/4pwakehm/ http://jsfiddle.net/4pwakehm/

It looks as though there are multiple issues here. 似乎这里有多个问题。

Firstly your selector must be '#my-calc' to correctly select the submit form. 首先,您的选择器必须为'#my-calc'才能正确选择提交表单。 Your jQuery code must be wrapped in a document ready handler (as per your added code), or the code needs to appear after the form. 您的jQuery代码必须包装在文档就绪处理程序中(根据您添加的代码),否则该代码需要出现在表单之后。 Also when you add a submit event handler then you need to return false to stop the form submitting. 同样,当您添加一个Submit事件处理程序时,您需要返回false来停止表单提交。 And lastly (and perhaps the most important), you cannot nest forms. 最后(也许是最重要的),您不能嵌套表格。 The @using (Html.BeginForm()) creates a form, and then you are creating another one inside it <form id="my-calc"> , this is not valid. @using (Html.BeginForm())创建一个表单,然后在其中创建另一个<form id="my-calc"> ,这是无效的。 What the browser will do is just ignore the inner one, so in other words, there will never be a submit event of the my-calc form, becuase the parent form is what is submitted. 浏览器将要做的只是忽略内部表单,换句话说,因为父表单是提交的表单,所以永远不会存在my-calc表单的Submit事件。

Also because you are just doing a calculation on the page with JavaScript, there is no real need for a form anyway, perhaps just a <button type="button" id="my-calc">Calculate</button> would be better with a click event. 另外,因为您只是使用JavaScript在页面上进行计算,所以实际上并不需要表单,也许只需<button type="button" id="my-calc">Calculate</button>会更好点击事件。

Now your calculate function also has errors 现在您的计算功能也有错误

every calculation line is missing a $ in the attempt to get the num1 value 尝试获取num1值时,每个计算行都缺少$

so 所以

$('#sum').val((parseInt(('#num1').val())) + parseInt($('#num2').val()));

should be 应该

$('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

and there is an additional issue with the multiplication one, the input is not #mult its #mul as per your @Html.TextBox("mul") . 而且乘法运算还有一个问题,根据@Html.TextBox("mul") ,输入不是#mult #mul

So all of that together, something like the following should resolve your issues 因此,所有这些共同解决了以下问题

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Sample Calculator</title>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $('#my-calc').on('click', function () {
                calculate();
            });

            function calculate() {
                //Add
                try {

                    $('#sum').val((parseInt($('#num1').val())) + parseInt($('#num2').val()));

                } catch (e) {

                }

                //Subtract
                try {

                    $('#sub').val((parseInt($('#num1').val())) - parseInt($('#num2').val()));

                } catch (e) {

                }

                //Multiply
                try {

                    $('#mul').val((parseInt($('#num1').val())) * parseInt($('#num2').val()));

                } catch (e) {

                }

                //Divide
                try {

                    $('#div').val((parseInt($('#num1').val())) / parseInt($('#num2').val()));

                } catch (e) {

                }
            }
        });
    </script>

</head>
<body>
    <div><h4>Sample Calculator</h4></div>
    <p> @Html.Label("Input 1") : @Html.TextBox("num1", "0")</p>
    <p> @Html.Label("Input 2") : @Html.TextBox("num2", "0")</p>
    <p> @Html.Label("Sum ") : @Html.TextBox("sum")</p>
    <p> @Html.Label("Sub ") : @Html.TextBox("sub")</p>
    <p> @Html.Label("Mult ") : @Html.TextBox("mul")</p>
    <p> @Html.Label("Div ") : @Html.TextBox("div")</p>
    <button id="my-calc" type="button">Calculate</button>  
</body>
</html>

Your code isn't working because you don't have # in your Javascript. 您的代码无效,因为您的Javascript中没有#

  • # should be in front of the name, to represent an Id . #应该在名称前面,代表一个ID
  • The . . should be in front of the name, to represent an class . 应该在名称前面,代表一个

You could is essentially do: 您基本上可以做:

$(document).ready(function () {
     $("#my-calc").on("click", function () {
          alert("Triggered alert for click.");
     });
});

Keep in mind that with $(document).ready utilizes jQuery. 请记住,使用$(document).ready使用jQuery。

That is an example, you should also use your console in the browser to help debug Javascript. 这是一个示例,您还应该在浏览器中使用console来帮助调试Javascript。 Which will help troubleshoot such issues. 这将有助于解决此类问题。

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

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