简体   繁体   English

数组中的重复元素-JavaScript

[英]Repeated elements in an array - javascript

I have been developing a code in javascript that you can select text and adding this selected text in an array. 我一直在用javascript开发代码,您可以选择文本并将此选择的文本添加到数组中。 When I select a text, a tooltip button is showed for you to adding this text selected in an array. 当我选择文本时,将显示一个工具提示按钮,供您添加在数组中选择的文本。 However, when I click in this button, for each iteration, it's adding n times the selected text, resulting in an array with repeated elements. 但是,当我单击此按钮时,对于每次迭代,它都会将选定文本添加n倍,从而导致包含重复元素的数组。

The array is the variable selects. 数组是变量选择。 The code that manipulate the array is this: 操纵数组的代码是这样的:

$("#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);
    }

Follow below the full code: 请遵循以下完整代码:

<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>

The problem is inside your function for mouseUp $('#element').mouseup(function(e) you have inserted the listener for the other action. 问题出在mouseUp $('#element').mouseup(function(e)您已为其他操作插入了侦听器。

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

Everytime there is a mouse up a new listener for the quote-place div is registered, so the second time there are two listener, the third three and so on. 每次有一个鼠标移到一个新的监听器上,即quote-place div被注册,因此第二次有两个监听器,第三个监听器,依此类推。 You need to move this out of the mouseUp function. 您需要将其移出mouseUp函数。

A possible different approach is, since you are adding your element in a dynamic way, to add and remove listeners in a dynamic way, using 一种可能的不同方法是,由于您是以动态方式添加元素的,因此可以使用以下方式以动态方式添加和删除侦听器:

document.getElementById("quote-place").removeEventListener("click", quote, true);
document.getElementById("quote-place").addEventListener("click", quote, true);

A working snippet 工作片段

 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM