如何使用 Javascript 将文本从文本区域移动到新表中

How would I move text from text areas into a new table using Javascript?

本文关键字:文本 移动 新表中 区域 Javascript 何使用      更新时间:2023-09-26

我只是在学习Javascript,我们的老师没有资格教他一生中从未使用过任何形式的代码。我想要一个 onClick 事件来触发一个函数,该函数将专用表中 3 个文本框的内容移动到用于打印的新表格上的特定位置。

这是具有三个文本区域的表的代码:

<table>
    <tr>
        <td rowspan="2">
            <textarea rows="19" cols="52"> Notes  directly from the source should go in this box. (copy and paste)</textarea>
        </td>
        <td> <textarea rows="3" cols="30">The URL or web-address of the source should go here.</textarea>
                    </td>
    </tr>
    <tr>
        <td> <textarea rows="15" cols="30">Additional notes should go in this box.</textarea>
        </td>
    </tr>
</table>

这个想法是将 3 段文本移动到数字记事卡上。URL 在顶部,直接注释在中间,学生的笔记在底部。所有的基本格式略有不同。使用一个onClick函数是否可以做到这一点,或者使用三个功能会容易得多。请记住,如果我确实使用了三个函数,我需要它们都由同一事件触发。

您可以使用 jQuery 并将内容从一个 HTML 节点复制/粘贴/删除到另一个 HTML 节点中:

$('#idOfYourTargetNode').text($('#idOfYourFirstNode').text());
$('#idOfYourFirstNode').empty();

只需给相应的元素一个喜欢:

<td id="url">Content url ....</td>

而你的目标像这样:

<h1 id="headlineUrl"> URL Headline </h1>

您可以在脚本标记中执行此操作:

$('#headlineUrl').text($('#url').text());
$('#url').empty();

触发它单击您的元素。不要忘记包含jQuery。

首先,如果文本区域具有可以引用的 id,这将是最简单的:

<tr>
<td rowspan="2">
    <textarea id="notes" rows="19" cols="52"> Notes  directly from the source should go in this box. (copy and paste)</textarea>
</td>
<td> <textarea id="address" rows="3" cols="30">The URL or web-address of the source should go here.</textarea>
            </td>

其他注释应在此框中。

然后,您可以执行以下操作:

$("button").on("click", function() {
  $("#newlocation1").text($("#notes").text());
  $("#newlocation2").text($("#address").text());
  $("#newlocation3").text($("#additional").text());
}

虽然,从这一点开始,您可以通过多种方式使用这些文本。

解决方案

var getValueBySelector = function(c){
  return document.querySelector(c).value;
};
var each = function(array, cb){
  for(var i=0; i<array.length; i++) cb.call(array[i], i, array[i]);
};
var concatenate = function(array, sep){
  var concat = [];
  each(array, function(){ 
    concat.push(getValueBySelector(this));
  });
  return concat.join(sep);
};
document.querySelector('.concat').innerHTML = concatenate(['.notes', '.url', '.add'], '<br>');
 <table>
      <tr>
        <td rowspan="2">
          <textarea class="notes" rows="19" cols="52"> Notes  directly from the source should go in this box. (copy and paste)</textarea>
        </td>
        <td> <textarea class="url" rows="3" cols="30">The URL or web-address of the source should go here.</textarea>
        </td>
      </tr>
      <tr>
        <td> <textarea class="add" rows="15" cols="30">Additional notes should go in this box.</textarea>
        </td>
      </tr>
    </table>
    <div class="concat"></div>