[英]jQuery val undefined
I'm trying to get the value of an input element on a html page using jQuery. 我正在尝试使用jQuery在html页面上获取输入元素的值。 I can get the element value using .val() if I call it from a script tag in the html page.
如果从html页面的脚本标签调用.val(),则可以获取元素值。 However, when I call the same function from a seperate js file it returns undefined .
但是,当我从单独的js文件中调用相同的函数时,它将返回undefined 。
Anyone have anyidea what is going on here? 有人有什么想法吗?
index.html index.html
$(document).ready(function() {
console.log($("#amount").val()); // This works
externalFunction(); // This returns undefined
});
file.js file.js
function externalFunction() {
console.log($("#amount").val());
}
EDIT 编辑
I should clarify that the div which contains the input element is hidden. 我应该澄清一下,包含输入元素的div是隐藏的。
style="display: none;"
Would this make a difference? 这会有所作为吗?
When I call the same function from a seperate js file it returns undefined.
当我从单独的js文件调用相同的函数时,它返回未定义。
This is the correct behaviour because you returned nothing. 这是正确的行为,因为您什么也没有返回 。
You have to use return
statement. 您必须使用
return
语句。
function externalFunction() {
return $("#amount").val();
}
let value=externalFunction();
console.log(value);
Use export statement or require
in order to make function visible in other file also. 也可以使用export语句或
require
以使功能在其他文件中可见。
As described in the question, that's simply not possible. 正如问题中所述,这根本不可能。
Instead, I suspect that you aren't calling externalFunction
at the same time you're calling the console.log
. 相反,我怀疑您不是在调用
console.log
的同时调用externalFunction
。 Instead, I suspect you're calling it earlier, before the input exists. 相反,我怀疑您在输入存在之前就调用了它。
There are only two reasons val
ever returns undefined
: val
返回undefined
原因只有两个:
You call it on an empty jQuery object (because nothing matched the selector, for instance, because you called the function too soon). 您可以在空的jQuery对象上调用它(例如,因为没有与选择器匹配的内容,因为调用该函数的时间过早)。
You call it on a jQuery object whose first element is not an input
or select
(and thus has no value
property). 您可以在第一个元素不是
input
或select
(因此没有value
属性)的jQuery对象上调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.