javascript JS:“类型错误:‘未定义’不是一个对象”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23817987/
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
JS: "TypeError: 'undefined' is not an object"
提问by user3666951
var name = $("input[#name]").value;
var email = $("input[#email]").value;
var msg = $("input[#msg]").value;
var nameLength = name.length;
var emailLength = email.length;
var msgLength = msg.length;
As you can see, all I'm trying to do is to get the length of the value of the #email field. It works for both of the other fields, but not the email field. It give "TypeError: 'undefined' is not an object".
如您所见,我所做的只是获取#email 字段值的长度。它适用于其他两个字段,但不适用于电子邮件字段。它给出“类型错误:'未定义'不是一个对象”。
Any reason why?
有什么理由吗?
I've tried in both Safari and Google Chrome, both gives the same error.
我在 Safari 和谷歌浏览器中都试过,都给出了同样的错误。
The HTML:
HTML:
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-5">
<input id="email" name="email" type="text" placeholder="Enter your email address
here" class="form-control input-md" required="">
</div>
</div>
回答by jfriend00
You are trying to use a DOM property on a jQuery object. If you have a jQuery object, then you must either use the jQuery method .val()
, not the DOM property .value
or you have to reach into the jQuery object to get the DOM object which you can then use DOM properties on.
您正在尝试在 jQuery 对象上使用 DOM 属性。如果您有一个 jQuery 对象,那么您必须使用 jQuery 方法.val()
,而不是 DOM 属性,.value
或者您必须访问 jQuery 对象以获取 DOM 对象,然后您可以在该对象上使用 DOM 属性。
I'd suggest you change it to use the jQuery method for getting the value:
我建议您将其更改为使用 jQuery 方法来获取值:
var name = $("input[#name]").val();
var email = $("input[#email]").val();
var msg = $("input[#msg]").val();
Or, for illustrative purposes, this would also work (get the DOM object out of the jQuery object and use .value
):
或者,出于说明目的,这也可以(从 jQuery 对象中取出 DOM 对象并使用.value
):
var name = $("input[#name]")[0].value;
var email = $("input[#email]")[0].value;
var msg = $("input[#msg]")[0].value;
Based on the HTML you've added to your question, you need to fix your selectors too. To target an id="xxx"
, you just use $("#xxx")
. No other part of the selector is required because ids must be unique in the entire document. So, if all your HTML works like the email part you've shown in your question, then you can use this:
根据您添加到问题中的 HTML,您还需要修复您的选择器。要定位id="xxx"
,您只需使用$("#xxx")
. 不需要选择器的其他部分,因为 id 在整个文档中必须是唯一的。因此,如果您的所有 HTML 都像您在问题中显示的电子邮件部分一样工作,那么您可以使用以下代码:
var name = $("#name").val();
var email = $("#email").val();
var msg = $("#msg").val();