【问题标题】:jQuery concatenate string to input fieldjQuery将字符串连接到输入字段
【发布时间】:2017-02-23 13:21:33
【问题描述】:

当我的表格中的 td 被点击时,我正在尝试连接字符串并将其显示到我的文本框中。

到目前为止我是这样做的:

   $(document).on("click", ".keywordClick", function () {
            $('.txtKeywords').val($(this).attr('value'));
        });

.keywordClick is td item which contains required string 

还有

.txtKeywords is the textbox which is empty initially...

每次有人点击字符串时,我希望它是这样的:

"Hello world today" => initial click;

"is a sunny day" => second click;

所以输出会是这样的:

Hello world 今天是晴天...每个连接的字符串之间应该有一个空格“”

【问题讨论】:

  • 为什么不把 JS 和 HTML 作为一个完整的文件发布呢?更容易理解您的问题并找到答案

标签: jquery string html-table concatenation


【解决方案1】:

您可以使用.val() 的回调函数,该函数具有返回要设置的值的函数。它接收集合中元素的索引位置和旧值作为参数。您可以使用旧值与新值连接:

$(document).on("click", ".keywordClick", function () {
 var appendText = " " + $(this).attr('value');
  $('.txtKeywords').val( function( index, oldVal ) {
     return oldVal + appendText;
  });
});

【讨论】:

    【解决方案2】:

          $(".keywordClick").on("click",function () {
             $('.txtKeywords').val($('.txtKeywords').val()+" "+$(this).html());
      
           });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
    <table>
     <tr>
        <th>Data</th>
      </tr>
      <tr>
        <td class="keywordClick">Hello world today</td>
        <td class="keywordClick">is a sunny day</td>
      </tr>
    </table>
    </div>
    <div>
    <input type="text" class= "txtKeywords">
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2014-04-29
      • 1970-01-01
      • 2014-03-31
      • 2015-10-27
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多