【问题标题】:JQuery get value from one td to anotherJQuery 从一个 td 获取值到另一个
【发布时间】:2012-11-20 11:08:10
【问题描述】:

我有这个代码

<table class="X">
  <tr>
    <td class="Y">Value</td>
  </tr>
</table>

<table class="Z">
  <tr>
    <td><input class="edit-Y" type="text"></td>
  </tr>
</table>

我需要使用类“Y”从 td 获取值,以便使用 jQuery 使用类“edit-Y”进行输入。 我尝试以不同的方式编写脚本,但每当我得到空字段或 [Object Object]。有什么想法吗?

谢谢!

【问题讨论】:

  • 发布您的尝试,以便我们快速回答问题。

标签: jquery input get html-table


【解决方案1】:

试试这个,

$('.edit-Y').val($('.Y').html());

评论的附加答案

如果你有下面这样的 html 并且你想选择 td 中的每个值并将其插入特定的输入框,

<table class="X">
  <tr>
    <td class="Y1">Value1</td>
    <td class="Y2">Value2</td>
    <td class="Y3">Value3</td>
  </tr>
</table>

<table class="Z">
  <tr>
    <td><input class="edit-Y1" type="text">
    <input class="edit-Y2" type="text">
    <input class="edit-Y3" type="text"></td>
  </tr>
</table>

jquery 会这样做,

$(function(){
 $('td[class^=Y]').each(function(){ 
    var tdValue = $(this).html();
    var id = $(this).attr('class');
    $('.edit-'+id).val(tdValue);
  });
});

【讨论】:

  • 它有效。如果我有 Y1,Y2,Y3,Y4 和 edit-Y1,edit-Y2,edit-Y3 行,我怎样才能最小化代码的大小而不是写 4 行相同的 jQuery 代码?
  • 实际上第二个表在点击按钮后弹出,所以类不是edit-y1/edit-y2。这只是编辑-y。例如,如果我单击按钮 #3,它会弹出 td 中的 Y3 类信息。
【解决方案2】:

更通用的方法:

$(".Z input").val(function() {
    return $(".X td." + this.className.split("-").pop()).text();
});

演示: http://jsfiddle.net/G3tBT/

【讨论】:

    【解决方案3】:

    $('.edit-Y').val( $('td.Y').text() );

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2015-08-16
      • 2018-11-15
      • 2021-10-03
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2021-05-04
      相关资源
      最近更新 更多