数组中的重复元素 - javascript

时间:2017-05-16 16:40:25

标签: javascript arrays

我一直在使用javascript开发代码,您可以选择文本并在数组中添加此选定文本。当我选择文本时,会显示工具提示按钮,您可以添加在数组中选择的此文本。 但是,当我单击此按钮时,对于每次迭代,它会将所选文本添加n次,从而生成包含重复元素的数组。

数组是变量选择。 操纵数组的代码是:

$("#quote-place").click(function quote() {
    var txt = [null];
    var txtSelected = window.getSelection();
    var txtRange = txtSelected.toString();

    if(txtRange.length >= 2) {
            if (window.getSelection) {
                txt = window.getSelection();
            } else if (document.getSelection) {
                    txt = document.getSelection();
            } else if (document.selection) {
                    txt = document.selection.createRange().text;
            }
            selects.push('' + txt);
    }

按照以下完整代码:

<html>

<head>

    <style type="text/css">
        #quote-place { position:absolute;  }
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/JavaScript">

    function snapSelectionToWord() {
        var sel;

        // Check for existence of window.getSelection() and that it has a
        // modify() method. IE 9 has both selection APIs but no modify() method.
        if (window.getSelection && (sel = window.getSelection()).modify) {
            sel = window.getSelection();
            if (!sel.isCollapsed) {

                // Detect if selection is backwards
                var range = document.createRange();
                range.setStart(sel.anchorNode, sel.anchorOffset);
                range.setEnd(sel.focusNode, sel.focusOffset);
                var backwards = range.collapsed;
                range.detach();

                // modify() works on the focus of the selection
                var endNode = sel.focusNode, endOffset = sel.focusOffset;
                sel.collapse(sel.anchorNode, sel.anchorOffset);

                var direction = [];
                if (backwards) {
                    direction = ['backward', 'forward'];
                } else {
                    direction = ['forward', 'backward'];
                }

                sel.modify("move", direction[0], "character");
                sel.modify("move", direction[1], "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", direction[1], "character");
                sel.modify("extend", direction[0], "word");
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            if (textRange.text) {
                textRange.expand("word");
                // Move the end back to not include the word's trailing space(s),
                // if necessary
                while (/\s$/.test(textRange.text)) {
                    textRange.moveEnd("character", -1);
                }
                textRange.select();
            }
        }
    }

    var selects = new Array();
    selects.push("1");

    $(document).ready(function() {
            var selectionImage;
            $('#element').mouseup(function(e) {
                if (!selectionImage) {
                    selectionImage = $('<button>').attr({
                        type: 'button',
                        title: 'Citar Texto seleccionado',
                        id: 'quote-place'

                    }).html("Add").css({
                        "color": "red"
                    }).hide();

                    $(document.body).append(selectionImage);
                }

                $("#quote-place").click(function quote() {
                    var txt = [null];
                    var txtSelected = window.getSelection();
                    var txtRange = txtSelected.toString();

                    if(txtRange.length >= 2) {
                            if (window.getSelection) {
                                txt = window.getSelection();
                            } else if (document.getSelection) {
                                    txt = document.getSelection();
                            } else if (document.selection) {
                                    txt = document.selection.createRange().text;
                            }
                            selects.push('' + txt);
                    }
                    document.menu.selectedtext.value = selects;

                }).mousedown(function() {

                    if (selectionImage) {
                        selectionImage.fadeOut();
                    }
                });

                selectionImage.css({
                    top: e.pageY - 30,
                    //offsets
                    left: e.pageX - 13 //offsets
                }).fadeIn();
            });
        });

</script>

</head>


<body>

    <div id="element" class="element" onmouseup="snapSelectionToWord()">
        Hello <b>her</b>e is some &nbsp; <i>nice text</i> Please try selecting some
        <p>Amet elementum, platea porta. Magna eros, pid velit? Pid urna nunc ut, amet duis ultrices vut ac nec mus phasellus tincidunt. Et penatibus augue. Proin ac urna, quis arcu ultrices, ut nunc! Ultrices et hac integer rhoncus a placerat sit? Auctor tristique tincidunt augue amet?</p>

    </div>

    <br><br>

    <form class="menu" name="menu">
        <textarea name="selectedtext" rows="5" cols="20"></textarea>
    </form>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

问题出在你为mouseUp $('#element').mouseup(function(e)设置的函数中,你已经为其他动作插入了监听器。

$("#quote-place").click(function quote()

每次有鼠标注册时,quote-place div的新监听器都会被注册,所以第二次有两个监听器,第三次有三个,依此类推。您需要将其移出mouseUp函数。

一种可能的不同方法是,因为您是以动态方式添加元素,所以使用

以动态方式添加和删除侦听器
document.getElementById("quote-place").removeEventListener("click", quote, true);
document.getElementById("quote-place").addEventListener("click", quote, true);

工作代码段

<html>

<head>

    <style type="text/css">
        #quote-place { position:absolute;  }
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/JavaScript">

    function snapSelectionToWord() {
        var sel;

        // Check for existence of window.getSelection() and that it has a
        // modify() method. IE 9 has both selection APIs but no modify() method.
        if (window.getSelection && (sel = window.getSelection()).modify) {
            sel = window.getSelection();
            if (!sel.isCollapsed) {

                // Detect if selection is backwards
                var range = document.createRange();
                range.setStart(sel.anchorNode, sel.anchorOffset);
                range.setEnd(sel.focusNode, sel.focusOffset);
                var backwards = range.collapsed;
                range.detach();

                // modify() works on the focus of the selection
                var endNode = sel.focusNode, endOffset = sel.focusOffset;
                sel.collapse(sel.anchorNode, sel.anchorOffset);

                var direction = [];
                if (backwards) {
                    direction = ['backward', 'forward'];
                } else {
                    direction = ['forward', 'backward'];
                }

                sel.modify("move", direction[0], "character");
                sel.modify("move", direction[1], "word");
                sel.extend(endNode, endOffset);
                sel.modify("extend", direction[1], "character");
                sel.modify("extend", direction[0], "word");
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            if (textRange.text) {
                textRange.expand("word");
                // Move the end back to not include the word's trailing space(s),
                // if necessary
                while (/\s$/.test(textRange.text)) {
                    textRange.moveEnd("character", -1);
                }
                textRange.select();
            }
        }
    }

    var selects = new Array();
    selects.push("1");

    $(document).ready(function() {
            var selectionImage;
            $('#element').mouseup(function(e) {
                if (!selectionImage) {
                    selectionImage = $('<button>').attr({
                        type: 'button',
                        title: 'Citar Texto seleccionado',
                        id: 'quote-place'

                    }).html("Add").css({
                        "color": "red"
                    }).hide();

                    $(document.body).append(selectionImage);
                }

                function quote() {
                    var txt = [null];
                    var txtSelected = window.getSelection();
                    var txtRange = txtSelected.toString();

                    if(txtRange.length >= 2) {
                            if (window.getSelection) {
                                txt = window.getSelection();
                            } else if (document.getSelection) {
                                    txt = document.getSelection();
                            } else if (document.selection) {
                                    txt = document.selection.createRange().text;
                            }
                            selects.push('' + txt);
                    }
                    document.menu.selectedtext.value = selects;
                    document.getElementById("quote-place").removeEventListener("click", quote, true);
                   document.getElementById("quote-place").removeEventListener("mousedown", fadeImage, true);

                }
                
                function fadeImage() {
                    if (selectionImage) {
                        selectionImage.fadeOut();
                    }
                    
                   
                }
                

                document.getElementById("quote-place").addEventListener("click", quote, true);
                document.getElementById("quote-place").addEventListener("mousedown", fadeImage, true);
                
                selectionImage.css({
                    top: e.pageY - 30,
                    //offsets
                    left: e.pageX - 13 //offsets
                }).fadeIn();
            });
        });

</script>

</head>


<body>

    <div id="element" class="element" onmouseup="snapSelectionToWord()">
        Hello <b>her</b>e is some &nbsp; <i>nice text</i> Please try selecting some
        <p>Amet elementum, platea porta. Magna eros, pid velit? Pid urna nunc ut, amet duis ultrices vut ac nec mus phasellus tincidunt. Et penatibus augue. Proin ac urna, quis arcu ultrices, ut nunc! Ultrices et hac integer rhoncus a placerat sit? Auctor tristique tincidunt augue amet?</p>

    </div>

    <br><br>

    <form class="menu" name="menu">
        <textarea name="selectedtext" rows="5" cols="20"></textarea>
    </form>

</body>
</html>