jquery split() 和 indexOf 导致“对象不支持此属性或方法"; [英] jquery split() and indexOf results in "Object doesn't support this property or method"
问题描述
我有以下代码:
var selected = $('#hiddenField').val().split(",");
...
if (selected.indexOf(id) > 0) {
... set value ...
}
我正在动态创建一个 CheckBoxList,并尝试通过将选定的 ID 放入隐藏字段来记住复选框的状态.
I'm dynamically creating a CheckBoxList, and trying to remember the state of the checkboxes by putting the selected IDs into the hidden field.
我收到一条错误消息,指出对象不支持此属性或方法".我的假设是 selected 是一个数组,它应该支持 indexOf.那不正确吗?
I get an error stating that "Object doesn't support this property or method". My assumption is that selected is an array, which should support indexOf. Is that incorrect?
推荐答案
有一个jQuery方法可以克服indexOf()
的不足,可以使用.inArray()
代替:
There's an jQuery method to overcome the lack of indexOf()
, you can use .inArray()
instead:
var selected = $('#hiddenField').val().split(",");
if ($.inArray(id, selected) > -1) {
... set value ...
}
jQuery.inArray()
就是因为这个原因而存在的……如果您已经包含了 jQuery,则无需再次编写该函数.注意:这实际上返回一个数字,就像 indexOf()
一样.
jQuery.inArray()
exists for just this reason...if you're including jQuery already, no need to write the function again. Note: This actually returns a number, like indexOf()
would.
这篇关于jquery split() 和 indexOf 导致“对象不支持此属性或方法";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!