Javascript 类型错误:.val 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29845871/
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 04:06:36  来源:igfitidea点击:

TypeError: .val is not a function

javascriptjquery

提问by Neil P

I have the following code, where I am selecting all matching elements that start with the same name, excluding one I do not want included in the group.

我有以下代码,我选择所有以相同名称开头的匹配元素,不包括我不想包含在组中的元素。

var myInputBoxes= $('input[id ^= "SubjectText"]').not('#SubjectTextNew');
for (i = 0 ; i < myInputBoxes.length; i++){
    var SubjectId = myInputBoxes[i].id.replace('SubjectText', '');
    var Subject = myInputBoxes[i].val();
}

This gives me the following error in firefox

这给了我在 Firefox 中的以下错误

TypeError: myInputBoxes[i].val is not a function

类型错误:myInputBoxes[i].val 不是函数

Why would it fail on the val function?

为什么它会在 val 函数上失败?

回答by Rory McCrossan

Accessing a jQuery object using bracket notation returns a DOMElement which does not have the val()function. If you want to retrieve an element by its index within a matched set you need to use eq():

使用括号表示法访问 jQuery 对象会返回一个没有该val()函数的 DOMElement 。如果要通过匹配集合中的索引检索元素,则需要使用eq()

var Subject = myInputBoxes.eq(i).val();

Alternatively you can retain the DOMElement and use the valueproperty:

或者,您可以保留 DOMElement 并使用该value属性:

var Subject = myInputBoxes[i].value;

回答by Arun P Johny

Because subjectBoxes[i]is not a jQuery object, if it is a jQuery object then you can use .eq() to get a jQuery wrapper reference to the element at the passed index

因为subjectBoxes[i]不是 jQuery 对象,如果它是 jQuery 对象,那么您可以使用 .eq() 获取对传递索引处的元素的 jQuery 包装器引用

var myInputBoxes = $('input[id ^= "SubjectText"]').not('#SubjectTextNew');
myInputBoxes.each(function (e, el) {
    var SubjectId = this.id.replace('SubjectText', '');
    var Subject = subjectBoxes.eq(i).val();
})