简体   繁体   English

动态创建输入时,模糊事件无法按预期工作

[英]blur event not working as expected with dynamically created inputs

I have a table which can have some dinamically created inputs, so the user can throw in some values and make some calculations: 我有一个可以包含一些动态创建的输入的表,因此用户可以输入一些值并进行一些计算:

<table>
   <thead>...</thead>
   <tbody>
     <tr>
        <td>Info</td>
        <td><input class="inputsTable"/></td>
        <td><input class="inputsTable"/></td>
   </tbody>
</table>

When the user inputs a value and the blur event occurs, the system would do some calculations. 当用户输入一个值并且发生模糊事件时,系统将进行一些计算。 I had the "multiple blur events firing" problem and i solved like this: 我遇到了“多个模糊事件触发”问题,我这样解决:

<script>
    $(document).ready(function () {        
        $(".inputsTable").mask("#.##0,00", { reverse: true });
        //setting up masks
    });

    let isBound = false;
    $('.inputsTable').on('input propertychange paste', function () {
        if (!isBound) {
            isBound = true;
            $(this).on('blur', function () {
                alert($(this).val());
            });
        }
    });

</script>

It works for the first input. 它适用于第一个输入。 If i try to fire the blur event from the second input, it won't work. 如果我尝试从第二个输入触发模糊事件,它将无法正常工作。 And if i reset the isBound variable: 如果我重置isBound变量:

$('.inputsTable').on('input propertychange paste', function () {
            if (!isBound) {
                isBound = true;
                $(this).on('blur', function () {
                    alert($(this).val());
                    isBound = false;
                });
            }
        });

Sometimes it works, but sometimes it will fire multiple times. 有时它可以工作,但有时它会触发多次。 How can i solve this? 我该如何解决?

Try this if it works. 如果可行,请尝试此操作。 If you are inserting or appending inputs dynamic then you should use document to reload the DOM. 如果要动态插入或添加输入,则应使用document重新加载DOM。

 $(document).on('.inputsTable','input propertychange paste', function () {
        if (!isBound) {
            isBound = true;
            $(this).on('blur', function () {
                alert($(this).val());
                isBound = false;
            });
        }
    });

OR 要么

 $(document).on('.inputsTable','input propertychange paste', function () {
         $(this).on('blur', function () {
            alert($(this).val());
         });
    });

But it would be fine if you upload the full code. 但是,如果您上传完整的代码,那就没问题了。

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

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