jQuery-object.id在未定义时未定义 [英] JQuery - object.id is undefined when it shouldn't be

查看:112
本文介绍了jQuery-object.id在未定义时未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JQuery,却遇到了这个奇怪的(也许是愚蠢的)错误.

I'm working with JQuery and i'm running into this strange (or perhaps stupid) error.

在我的HTML中,我有:

In my HTML I have:

<input type="password" name="repeatPassword" id="id_repeatPassword" /> 

然后在我的JavaScript代码中,我有:

And then in my javascript code i have:

validateRepeatPassword($('#id_repeatPassword'));

不幸的是在函数"validateRepeatPassword"中:

Unfortunately in the function "validateRepeatPassword":

function validateRepeatPassword(o) {
        // this works
        if (o.value == $("#id_password").val()) {
        // this returns "undefined"
        alert(o.id)
...
}

为什么?

推荐答案

o是对jQuery对象的引用,而不是DOM元素引用.在您的validateRepeatPassword函数内部,执行以下操作:

o is a reference to a jQuery object, NOT a DOM element reference. Inside your validateRepeatPassword function do:

alert( $(o).attr('id') );

如果要从jQuery对象访问直接DOM元素的属性,

If you want to access the direct DOM element's property from the jQuery object,

alert( o[0].id )

alert( o.get(0).id );

这篇关于jQuery-object.id在未定义时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆