首页 > 解决方案 > 制作按钮(或复选框)并从中复制值以制作值列表

问题描述

我需要用电视节目、按钮或复选框上的名称制作一个简单的应用程序,当我单击多个按钮(或选择复选框)时,它会将值从它们复制到文本区域,然后我可以在其他地方复制和使用。

例如,我可能有 5 个按钮,分别命名为 MTV、MTV2、FOX、CNN、ZDF。例如,当我单击其中的 3 个(MTV、FOX、MTV2)时,我会进入以下文本区域:MTV;狐狸; MTV2(这样我就可以复制所需的电视节目列表)。

我在 HTML 中找到了代码(如下),但我不知道如何让电视节目留在 textarea 中,每次我点击新的电视节目时,它只显示该节目 - 它不会制作节目列表。

<html>
   <head>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script type="text/javascript">
         $(document).ready(function(){<!--  w w  w. j a  v a2  s.  c  om-->
         $("button").click(function () {
         var text = $(this).text();
         $("input").val(text);
         });
         });
      </script>
      <style>
         .selected { color:red; }
         .highlight { background:yellow; }
      </style>
   </head>
   <body>
      <div>
         <button>HRT1</button>
         <button>HRT2</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
         <button>NovaTV</button>
      </div>
      <input type="text" value="click a button" />
   </body>
</html>

标签: copy-paste

解决方案


干得好。您需要在每次单击时将文本与每一行连接起来以保留它。

$(document).ready(function(){

    var textForInput= "";

$("button").click(function () {
    var text = $(this).text();

    textForInput = textForInput.concat(text + " ");
    $("input").val(textForInput);
});
});
</script>
<style>
.selected { color:red; }
.highlight { background:yellow; }
</style>
</head>
<body>
<div>
<button>HRT1</button>
<button>HRT2</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
<button>NovaTV</button>
</div>
<input type="text" value="click a button" />
</body>
</html>

推荐阅读