我正在尝试获取在 Javascript 中设置为可编辑的标签的值。代码如下
<td class="cent" contenteditable='true' id="value_per_visit"
onchange="myFunction()"> -- </td>
这是我的 JavaScript 代码
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("value_per_visit").value;
document.getElementById("value_per_visit").innerHTML ="gotit";
alert("asad");
}
</script>
但我无法达到该功能。有什么解决办法吗?
最佳答案
我实际上不确定是否可以向 td 元素添加 onchange 或 oninput 事件属性..
oninput 属性在 or 元素的值发生更改时触发。 oninput 事件与 onchange 事件类似,但是 oninput 事件在元素的值更改后立即发生,而 onchange 在元素失去焦点时发生。另一个区别是 onchange 事件也适用于“keygen”和“select”元素。 https://www.w3schools.com/tags/ev_oninput.asp
读到您似乎无法将 oninput 或 onchange 与 <td>
一起使用
在你的元素上添加一个事件监听器应该可以解决问题,我认为这更干净,因为不需要在你的底层 html 中添加额外的功能。
//html
<table>
<td class="cent" contenteditable='true' id="value_per_visit">data here</td>
</table>
//js
var td = document.getElementById('value_per_visit')
td.addEventListener('input', function(){
console.log(td.innerHTML)
})
关于javascript - 通过onchange函数获取可编辑<td>标签的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310286/