javascript 如何为多个文本区域标记tabindex上选中的默认值?

rur96b6h  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(99)

我有几个文本区域,当我点击它的时候,我想得到默认的文本。对于一个文本区域,我找到了一个脚本,我适应了我的情况,但不是一个优雅的解决方案。我怎么能缩短它呢?

<script type="text/javascript">
    var textBox1 = document.getElementById("textarea_1");
    var textBox2 = document.getElementById("textarea_2");
    var textBox3 = document.getElementById("textarea_3");

    textBox1.onfocus = function() {
        textBox1.select();
        // Work around Chrome's little problem
        textBox1.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox1.onmouseup = null;
            return false;
        };
    };
    textBox2.onfocus = function() {
        textBox2.select();
        textBox2.onmouseup = function() {
            textBox2.onmouseup = null;
            return false;
        };
    };
    textBox3.onfocus = function() {
        textBox3.select();
        textBox3.onmouseup = function() {
            textBox3.onmouseup = null;
            return false;
        };
    };
</script>
nx7onnlm

nx7onnlm1#

您可以添加一个专用的类名,并使用类名作为选择器来重构代码,使其更具通用性,并使它适用于多个textareas,如下所示:

// Add the class 'auto-selectable' to the desired <texarea/> elements
var textBoxes = document.getElementByClassName('auto-selectable');

for(var i = 0; i < textBoxes.length; i++) {
  var textBox = textBoxes[i];
   
  textBox.select();
  
  // Work around Chrome's little problem
  textBox.onmouseup = function() {
    // Prevent further mouseup intervention
    textBox.onmouseup = null;
    
    return false;
  };
}

相关问题