【问题标题】:Get value of editable <td> tags through onchange function?通过 onchange 函数获取可编辑 <td> 标签的值?
【发布时间】:2022-02-10 10:06:28
【问题描述】:

我正在尝试获取在 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>

但我无法使用该功能。有什么解决办法吗?

【问题讨论】:

标签: javascript html-table onchange


【解决方案1】:

我实际上不确定你是否可以将 onchange 或 oninput 事件属性添加到 td 元素..

oninput 属性在 or 元素的值发生更改时触发。 oninput 事件类似于 onchange 事件,但是 oninput 事件在元素的值发生更改后立即发生,而 onchange 事件在元素失去焦点时发生。另一个区别是 onchange 事件也适用于“keygen”和“select”元素。 https://www.w3schools.com/tags/ev_oninput.asp

读到您似乎不能对&lt;td&gt; 使用 oninput 和 onchange

在你的元素上添加一个事件监听器应该可以解决问题,我认为这更简洁,因为不需要在你的底层 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)
})

【讨论】:

    【解决方案2】:

    最好的方法是在 td 元素内进行输入:

    <table>
    <tr>
      <td>
        <input  id="Test" value="0" />
      </td>
    </tr>
    </table>
    

    并在其上绑定更改事件:

    $('#Test').change(function(){
        alert($(this).val());
    })
    

    【讨论】:

      【解决方案3】:

      使用 onblur 代替 onchange 对我有用!

      --

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签