【问题标题】:DOM onselect failing to work properlyDOM onselect 无法正常工作
【发布时间】:2015-02-24 13:32:33
【问题描述】:

我正在使用如下定义的文本区域:

<textarea id="description"></textarea>

我正在尝试检测用户何时选择了某些文本,onselect 似乎非常适合这一点。它在 w3schools 示例中完美运行,我将其作为:

<textarea id="description" onselect="alert('testing');"></textarea>

但是当我把它改成我自己的函数时,什么都没有发生。

我已经尝试过使用: document.getElementById("description").addEventListener("onselect", getSelection("description"));

这会在页面加载时执行,当我选择文本时什么也不做。

我刚刚在函数中添加了一些简单的东西来尝试让它工作,我已经测试了我的动作选择代码,这很好。我只是无法让它运行 onselect 事件。这是我测试的getSelection 函数。

function getSelection(ele)
{
    var ele = document.getElementById(ele);

    var txt = "Text Selected";

    console.log(txt);
}

有什么想法吗? onselect 上的信息似乎很少,人们发现大多数资源都认为它是用于选择标签的。

【问题讨论】:

    标签: javascript html textarea textselection onselect


    【解决方案1】:

    您必须传递对该函数的引用,现在您只需使用() 立即调用该函数。此外,要使用addEventListener 添加事件,您必须使用select 而不是onselect

    document.getElementById("description").addEventListener("select", getSelection);
    
    function getSelection(event)
    {
        var ele = event.target;
    
        var txt = "Text Selected";
    
        alert(txt);
    }
    <textarea id="description"></textarea>

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多