我正在尝试将 .val()
转换为 .text()
,反之亦然。
我真的不知道我哪里错了。
$('#result').on('click','.update',function() {
var valval = $(this).closest('tr').find('td:eq(1)').val();
$(this).closest('tr').find('td:eq(1)').text(valval);
});
这是链接,希望您先打开它。我将不胜感激任何可以帮助我工作的答案。
这是JSFiddle .
最佳答案
您需要获取 input
元素的值,现在您正在对 td
元素调用 .val()
$(function() {
$('#result').on('click', '.update', function() {
var $td = $(this).closest('tr').find('td:eq(1)'),
$input = $td.find('input');
if ($input.length) {
$td.text($input.val());
} else {
$td.html($('<input />', {
value: $td.text()
}))
}
});
})
body {
margin: 20px;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1' id='result'>
<tr>
<td>hi there</td>
<td>
<input type='text' value="hello there" />
</td>
<td>
<button class='update'>update</button>
</tr>
<tr>
<td>hi there</td>
<td>hello there</td>
<td>
<button class='update'>update</button>
</tr>
</table>
关于jquery - .val() 到 .text() 使用/与最接近并查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33359675/