0

我正在使用 push 方法向现有数组 (st[]) 添加新值。添加一个新值是可行的,但是数组中的所有值都将获得最后添加的元素的值。

if(!window.WordCatcher){
    WordCatcher = {};
}

WordCatcher.selector = {};

WordCatcher.selector.getSelected = function(){
    var t = '';
        if(window.getSelection) {t = window.getSelection();}
        else if(document.getSelection) {t = document.getSelection();}
        else if(document.selection) {t = document.selection.createRange().text;}
    return t;
}


st = new Array();

WordCatcher.selector.dblclick = function() {
    st.push(WordCatcher.selector.getSelected());
    console.log(st);
}

在 jQuery 中调用函数:

$(document).bind("dblclick", WordCatcher.selector.dblclick);

示例:如果我双击第一个“Die”,第二个“Smart”,第三个“TV”,我将在 firebug 中得到以下日志:

[Die { constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}] [Smart {constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}, Smart {constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}] [TV { constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}, TV {constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}, TV {constructor=Selection,  focusNode=textNode,  anchorNode=textNode,  mehr...}]

也许有人知道我在做什么工作。

最好的问候,安迪

4

2 回答 2

1

我认为您推动了对“t”的引用。

每次更改时-所有数组元素都在更改,因为它们都引用相同的参数=>“t”。

问题可能出在您的函数中:WordCatcher.selector.getSelected

尝试更改它以返回其他内容,然后再次检查。

于 2013-02-24T09:48:18.313 回答
0

内部窗口的选择对象是一种单例,即每个 getSelection() 调用都返回对同一对象的相同引用。因此,您必须手动获取所需的所有数据,或克隆对象,但不要存储即时结果。

于 2013-02-24T10:17:16.150 回答