JQuery 使用相应的文本选择自动填充 table 行?

JQuery autofill table row with corresponding text selection?

我之前的问题在这里,但似乎仅使用 window 和文档无法完成。我想要的是,当第一行的文本被选中时,第一个输入将被填充。第二行也一样。

javascript - select text in table cell and autofill the input on the same row

https://jsfiddle.net/nrdq71pz/6/

<table>
<tr>
<td>Test code 1</td>
<td>
  <input type='text' id='input1' class="selection" />
</td>
</tr>
<tr>
<td>Test code 2</td>
<td>
    <input type='text' id='input2' class="selection" />
</td>
</tr>
</table>

我无法弄清楚你在问什么,但这能完成工作吗?当您点击 "Test code 1" 时,它会将输入值填入 "Hello"。

https://jsfiddle.net/nrdq71pz/8/

Html:

<table>
  <tr>
    <td class="select">Test code 1</td>
    <td>
      <input type='text' id='input1' class="selection" />
    </td>
  </tr>
  <tr>
    <td>Test code 2</td>
    <td>
      <input type='text' id='input2' class="selection" />
    </td>
  </tr>
</table>

jQuery:

$('.select').click(function(){
    $('#input1').val("hello")
})

我刚刚注意到您对上面 post 的评论。我认为我所做的是错误的,所以看看我在这里所做的并告诉我哪个更接近您的需要。 https://jsfiddle.net/nrdq71pz/9/

这是jQuery解决方案。 (实际上比我想象的要容易,我认为元素内的选择文本不能那么容易地到达,但是......):

$('td').on('mouseup',function() {
if (window.getSelection){ 
     s = window.getSelection().toString()
    }
$(this).next().find('input').val(s);
});

演示:

$('td').on('mouseup',function() {
if (window.getSelection){ 
     s = window.getSelection().toString()
    }
$(this).next().find('input').val(s);
});
td {
  padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Test code 1</td>
<td>
  <input type='text' id='input1' class="selection" />
</td>
</tr>
<tr>
<td>Test code 2</td>
<td>
<input type='text' id='input2' class="selection" />
</td>
</tr>
<tr>
<td>Test code 3</td>
<td>
<input type='text' id='input3' class="selection" />
</td>
</tr>
</table>

所以,重点是将事件放在单元格上,然后到达最近的输入(在您当前的 hTML 结构中,这有效,如果您更改某些内容,您可以轻松修改它,我猜)