Javascript jQuery 中 val.length 和 val().length 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33301069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:55:52  来源:igfitidea点击:

Difference between val.length and val().length in jQuery?

javascriptjquery

提问by Mayank Vadiya

What is difference between $("#id").val.lengthand $("#id").val().length?

$("#id").val.length和 和有什么不一样$("#id").val().length

When I write $("#id").val.lengththen the output is 1and $("#id").val().lengththen the output is the length of the written characters.

当我写$("#id").val.length那么输出是1$("#id").val().length然后输出是书写字符的长度。

What is the explanation?

解释是什么?

回答by Tushar

$("#id").valreturns the function definition of valand lengthof a function is the number of parameters the function is expectingas the valtakes one parameter(setterto set the value) the length is 1, whereas val()will invoke the function and get the returned value and lengthon it will return the number of characters in the value.

$("#id").val返回函数的函数定义vallength函数是函数期望的参数数量,因为val接受一个参数(setter设置值),长度为 1,而val()将调用函数并获取返回值,length然后将返回值中的字符数。

The correct use is $(selector).val().length

正确的用法是 $(selector).val().length

I will also recommend to use VanillaJS's trimor jQuery's $.trimon val()before checking lengthto remove leading and trailing spaces.

我还将建议在检查删除前导和尾随空格之前使用 VanillaJS 的修剪或 jQuery 的$.trimon 。val()length

回答by Milind Anantwar

Let us have a look at both the code:

让我们看看这两个代码:

Case 1:

情况1:

$("#id").val.length

Here .val return the method definition for .val(). and .length along with it returns number of maximum argument methods accepts(for example 2 for .toggleClass())

这里 .val 返回 的方法定义.val()。和 .length 连同它返回最大参数方法接受的数量(例如 2 for .toggleClass()

Case 2:

案例2:

$("#id").val().length

Here .val()returns the method evaluation result i.e. value of DOM object in string format and .length returns the length string value returned.

这里.val()以字符串格式返回方法评估结果即DOM对象的值,.length返回返回的长度字符串值。

Correct way:

正确做法:

Case 2 is the correct way of using .val()along with length as it returns length of value of element associated to it.

情况 2 是.val()与 length 一起使用的正确方法,因为它返回与其关联的元素值的长度。

回答by Marcus

With $("#id").valyou get the function (the source code) and with $("#id").val()this function will be called and executed.

有了$("#id").val这个函数(源代码),$("#id").val()这个函数就会被调用和执行。