简体   繁体   English

更改 div 标签的值时如何使用 on() 方法激活事件?

[英]How to activate an event with on() method when the value of a div tag is changed?

I am currently writing HTML and JS code in the following form, but when I put a new value in the div tag value, the event does not happen.我目前正在编写以下形式的 HTML 和 JS 代码,但是当我在 div 标签值中放入一个新值时,该事件不会发生。

the Javascript code is Javascript代码是

$('#CdText').on('input', function () {
    $('#CdText').innerHTML = concat($('#CdText').innerHTML, 'test');
});

HTML is HTML 是

<div id="CdText" class="ui-state-highlight" contenteditable="true">1234</div>

The above code does not work.上面的代码不起作用。
However it works但是它有效

$('#appInput').on('input', function () {
   $('#appInput').val(concat($('#appInput').val(), 'test'));
});

because HTML is因为 HTML 是

<input id="appInput" class="form-control ap-input">
  <div>1234</div>
</input>

By the way, changing $('#CdText').on('input', function () { as follows did not work.顺便说一句,更改 $('#CdText').on('input', function () { 如下不起作用。
$('#CdText').on('div', function () { $('#CdText').on('div', function () {
$('#CdText').on('change', function () { $('#CdText').on('change', function () {
$('#CdText').on('change', 'div', function () { $('#CdText').on('change', 'div', function () {

I hope I'm doing something wrong with Jquery's use of the on() method, but as of yet I haven't found what's wrong.我希望我在使用 Jquery 的 on() 方法时做错了,但到目前为止我还没有发现问题所在。

If you know how to write an event to be triggered every time something is entered into a div like the above, please let me know.如果您知道如何编写一个事件以在每次将某些内容输入到上述 div 时触发,请告诉我。

By the way, $('#CdText').on('input', function () { is properly contained in $(function () {}).顺便说一句,$('#CdText').on('input', function () { 正确地包含在 $(function () {}) 中。
css of CdText div tag is inline-block. CdText div 标签的 css 是 inline-block。 so it can write as input.所以它可以写为输入。

Thank you for reading.感谢您的阅读。

您可以在使用.on('input')收听时使用contenteditable属性,但是.innerHTML是为 vanilla JS 制作的,对于 jQuery,您应该使用.html()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM