1

如果没有数百行代码,将很难解释这一点,但我会尝试!

我有一个包含子对象数组的父对象。父级使用此函数将 MULTIPLE 选择元素写入页面

function writecollectionmultiselect(name,displayname,selectedrange){    

// Create select page element
var collection = $("<select/>");
collection.attr("name",name);
collection.attr("MULTIPLE","multiple");

// Loop over elements in this collection and ask them to draw themselves
for(var i=0; i<this.objectarray.length;i++){
    collection.append(this.objectarray[i].writemultioption(selectedrange));
}
return collection;
}

父母要求每个孩子根据他们的id是否在'selectedrange'中绘制自己的选项元素

function writemultioption(selectedrange){
    var option = $("<option/>");
    option.val(this.data.id);
option.html(this.data.name);
if(selectedrange.indexOf(parseInt(this.data.id)) >= 0){
    option.attr('selected', 'selected');
}
return option;
}

当 selectedrange 提供为 selectedrange=[1,2,3] 时,这工作正常但是,如果我使用 jquery 读取页面元素的选定值

selectedrange = $('[name='+myname+"]").val();

当我尝试调用第一个函数时,indexOf 函数似乎完全崩溃了。我添加了这行调试代码

alert("looking for "+this.data.id+" in "+selectedrange+" result "+selectedrange.indexOf(parseInt(this.data.id)))

当我第一次绘制选择器时,我得到了这个:

在 1,2,3 结果 0 中寻找 1

但是,读取值并重绘给出

在 1,2,3 结果中寻找 1 -1

我怀疑存在某种数据类型问题,但是几个小时以来我一直在努力解决这个问题。任何帮助表示赞赏。

4

2 回答 2

1

jQuery 将为您提供一个字符串数组,并且您将this.data.id使用转换为数字,parseInt因此它们永远不会匹配,因为indexOf比较是严格的。

一种解决方案是将字符串数组转换为数字。

selectedrange = $.map($('[name='+myname+"]").val(), function(n) { 
                                                        return parseInt(n, 10);
                                                    });

或者另一种解决方案是将数组保留为字符串,但摆脱parseInt并执行此操作。

if(selectedrange.indexOf(this.data.id) >= 0){
于 2012-08-16T15:41:34.377 回答
0

indexOf()函数将字符串作为参数,在您的示例中,您传入一个整数,尽量不要调用parseInt()

alert("looking for " + this.data.id + " in " + selectedrange + "result" + selectedrange.indexOf(this.data.id))
                                                                                      // no parseInt() here

此外,您得到的原因-1是因为该indexOf()函数-1在它正在搜索的字符串中找不到匹配项时返回。

于 2012-08-16T15:44:34.033 回答