【问题标题】:Collect selected test strings in HTML page via JavaScript通过 JavaScript 在 HTML 页面中收集选定的测试字符串
【发布时间】:2014-01-14 13:47:56
【问题描述】:

在 HTML 页面中,我想将用户选择的文本字符串收集到一个数组中,然后可以将其导出为 CSV 文件。

到目前为止,我已经想出了以下 JavaScript 来将选定的文本字符串收集到一个全局变量中:

var $labels = [];

function getSelText() {

    if (window.getSelection) {
    txt = window.getSelection();
    } else if (document.getSelection) // FireFox
    {
    txt = document.getSelection();
    } else if (document.selection) // IE 6/7
    {
    txt = document.selection.createRange().text;
    } else return;
    if (txt != '') {
    $labels.push(txt);
    }

    document.aform.selectedtext.value = $labels.toString();
}

我使用下面的 HTML sn-p 来测试它:

<input type="button" value="Get selection" onmousedown="getSelText()">
<form name=aform>
    <textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
<p>   
Lorem ipsum dolor sit amet,

另见以下 JSFiddle http://jsfiddle.net/mhzrP/

上述代码的问题在于,即使选择不同的文本字符串并将它们添加到数组中,数组的每个条目似乎都是相同的。

如果出现问题,我将不胜感激。另外,如果有人对从数组生成 CSV 文件有一些提示,我将不胜感激。谢谢!

【问题讨论】:

    标签: javascript html arrays csv


    【解决方案1】:

    使用此代码,经过测试并且可以正常工作:

        var $labels = [];
    
    function getSelText() {
    
        if (window.getSelection) {
            txt = window.getSelection();
        } else if (document.getSelection) // FireFox
        {
            txt = document.getSelection();
        } else if (document.selection) // IE 6/7
        {
            txt = document.selection.createRange().text;
        } else return;
        if (txt != '') {
            $labels.push(txt.toString());
        }
    
        document.aform.selectedtext.value = $labels;
    

    同意@Blacksheep 代码。将 .join() 添加到 $labels。

    document.aform.selectedtext.value = $labels.join();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多