ユーザーがボタンをクリックしたときに、テキストエリア内のテキストにタグを付けるために使用される JavaScript があります。今のところ、1つのボタンでしか機能しません。合計で 8 つのボタンにタグ付けできるようにする必要がありますが、ボタン ID ごとに同じコードを何度も繰り返したくないので、for ループを試しましたが、うまくいきませんでした。理由はよくわかりませんが。
これらはボタン ID です: edit-button0、edit-button1、edit-button2、...、edit-button8
ボタン ID をチェックするために for ループにアラートを追加しました。
後でどのボタンをクリックしても、ボタンIDはedit-button8であり、そのボタンに接続されたタグが追加されます。
これが機能しない理由、または代わりにどのようにすべきかについてのアイデア。
/*globals document*/
(function ($) {
"use strict";
$(document).ready(function () {
for (i=0;i<8;i++) {
$("#edit-button"+i).click(function () {
alert("#edit-button"+i);
var tag = $("#edit-button"+i).attr("value");
var id = "protocol"; /* id of textarea */
var element = document.getElementById(id); /* HTML element object */
var start = element.selectionStart; /* start pos of selection */
var end = element.selectionEnd; /* end pos of selection */
var text = element.value; /* whole text */
var prefix = text.substring(0, start); /* part before selection */
var selected = text.substring(start, end); /* selected text */
var suffix = text.substring(end); /* part after selection */
/* insert tags in selection */
selected = "["+tag+"]" + selected + "[/"+tag+"]";
/* update HTML object */
element.value = prefix + selected + suffix; /* selected text */
element.selectionStart = start; /* new start pos */
element.selectionEnd = start + selected.length; /* new end pos */
return false;
});
}
});
})(jQuery);