我试图将文本从 div
内部移动到输入字段的 value
中,但我得到了 [object Object]
作为输出。谁能解释一下为什么吗?
input = $('#input').contents();
$('#output').val(input);
最佳答案
斯宾塞。
.contents()方法不会为您提供文本,而是一个包含其所包含元素集合的对象。你应该使用:
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method.
您要查找的行是:
$('#input').val($('#div').text());
可以这样分解:
var textToMove = $('#div').text();
$('#input').val(textToMove);
这是一个完整的示例:
function move(){
$('#input').val($('#div').text()); //copy text
$('#div').text(''); //erase text
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input' type='text' value=''>
<div id="div">Hello, Spencer</div>
<button onclick='move()'>Click to move text</button>
关于javascript - 如何将文本从 div 移动到输入值中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50359118/