0

我在网上找到了下面的代码来将项目符号点添加到 textarea,它对于单个 textarea 非常有效。

脚本

var CRLF = 10;
var BULLET = String.fromCharCode(45);

function Init() {
    var textareas = document.querySelectorAll('textarea');
        [].forEach.call(textareas, function(element) {
            element.addEventListener("input", OnInput, false);
        });
}

function OnInput(event) {
    char = event.target.value.substr(-1).charCodeAt(0);
    nowLen = txt.value.length;

    if (nowLen > prevLen.value) {
        if (char == CRLF) txt.value = txt.value + BULLET + " ";
        if (nowLen == 1) txt.value = BULLET + " " + txt.value;
    }
    prevLen.value = nowLen;
}

HTML

<body onload="Init ();">
    <h4>Automatic bullets in a text box</h4>
    <textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
    <input type="hidden" id="prevLen" value="0"/>
</body>

但是,我不知道如何创建一个类似的函数,以便我可以在多个文本区域上使用它。

我想要一些可以通过隐藏输入的 id 的东西,所以我可以指定将项目符号添加到哪个输入的方式,但无法获得有效的解决方案。

欢迎提出建议/解决方案。

4

2 回答 2

0

我的查询/问题的解决方案:

脚本/app.js:

var CRLF   = 10;
var BULLET = String.fromCharCode(45);

function Init() {

var wrappers = document.querySelectorAll('panel-body');
    [].forEach.call(wrappers, function(wrapper) {
       var textarea = wrapper.querySelector("textarea"),
       input = wrapper.querySelector("input");
       textarea.addEventListener("input", OnInput(), false);
    });
}

function OnInput(ta,inp) {
    char = ta.value.substr(-1).charCodeAt(0);
    nowLen = ta.value.length;

    if (nowLen > inp.value) {
        if (char == CRLF) ta.value = ta.value + BULLET + " ";
        if (nowLen == 1) ta.value = BULLET + " " + ta.value;
    }
    inp.value = nowLen;
}

HTML

<body onload="Init ();">
<div class="panel-body">
<h4>Automatic bullets in a text box</h4>
<textarea id="ta1" oninput="OnInput(ta1, pv1);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv1" value="0"/>

    <h4>Automatic bullets in a text box</h4>
    <textarea id="ta2" oninput="OnInput(ta2,pv2);" rows="15" cols="40"></textarea>
    <input type="hidden" id="pv2" value="0"/>
</div>
</body>

上述解决方案解决了向多个文本区域添加项目符号的问题。

于 2016-04-28T09:56:30.367 回答
0

获取所有文本区域的列表并添加事件监听器

var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
    element.addEventListener("click", OnInput, false);
});

您可以使用任何有效的 CSS3 选择器来获取所需的文本区域。

根据您的编辑:您可以将元素组合在一起,以便您可以将它们作为一个组访问。现在您可以以任何您喜欢的方式使用输入。

<div class="some_wrapper">
   <textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
   <input type="hidden" id="prevLen" value="0"/>
</div>

var wrappers = document.querySelectorAll('some_wrapper');
[].forEach.call(wrappers, function(wrapper) {
   var textarea = wrapper.querySelector("textarea"),
       input = wrapper.querySelector("input");
   //process "input" to get the desired "id", "class",.....
   textarea.addEventListener("click", function(e) {
        OnInput(e, input)
   }, false);
});
于 2016-04-28T08:23:31.477 回答