简体   繁体   English

我将我的 Jquery 反转为 Javascript,但我不明白为什么这种语法有效?

[英]I reversed my Jquery to Javascript, but I don't understand why this syntax works?

So my goal was to reverse this jquery into javascript.所以我的目标是将这个 jquery 反转为 javascript。 Here is the jquery这是 jquery

    create: function (e) {
            var $input = $(e.target);
            var val = $input.val().trim();

            if (e.which !== ENTER_KEY || !val) {
                return;
            }

            this.todos.push({
                id: util.uuid(),
                title: val,
                completed: false
            });

            $input.val('');

            this.render();
        },

Now here is the same code that I converted into javascript现在这里是我转换成 javascript 的相同代码

create: function (e) {
            var input = e.target.value;
            var val = input.trim();

            if (e.which !== ENTER_KEY || !val) {
                return;
            }

            this.todos.push({
                id: util.uuid(),
                title: val,
                completed: false
            });

            val;

            this.render();
        },

So my Javascript code works and I understand 90% of it, but what I don't get is the 2nd to last line that just says "val;"所以我的 Javascript 代码有效,我理解其中的 90%,但我没有得到的是倒数第二行,它只是说“val;”。

I went through the debugger and tried to understand it, but I don't get the reason it's placed there and why it's even necessary?我通过调试器并试图理解它,但我不明白它放在那里的原因以及为什么它甚至是必要的?

The goal is whenever I input a value to my todo-list, it will show up on my screen.目标是每当我在我的待办事项列表中输入一个值时,它就会显示在我的屏幕上。 The code works fine, but I don't understand the purpose of the "val;"?代码工作正常,但我不明白“val;”的用途?

Wouldn't the this.todos.push automatically add the value to my array? this.todos.push 不会自动将值添加到我的数组中吗? Or why wouldn't I add "return val;"或者我为什么不添加“return val;” instead?反而?

I guess that previous $input.val('');我猜以前$input.val(''); was used to empty the input field after pushing its value to the array, but in your js code it is useless that val;用于在将其值推送到数组后清空输入字段,但在您的 js 代码中, val; statement.陈述。

Furthermore, the jquery code $input.val('');此外,jquery 代码 $input.val(''); refers to the input DOM element, however in your js code the val statement just points to a local variable of your function.指输入 DOM 元素,但是在您的 js 代码中,val 语句仅指向 function 的局部变量。 If you want to replicate the previous behaviour you should do something like this: input='' instead of the val;如果你想复制以前的行为,你应该这样做: input=''而不是val;

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

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