简体   繁体   English

Javascript replace()函数在jQuery UI对话框中不起作用

[英]Javascript replace() function not working in jQuery UI Dialog

I've been using javascript replace() with to limit input to digits and a single decimal like this: 我一直在使用javascript replace()将输入限制为数字和一个小数,如下所示:

<input id="dialog-input" type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" \>

This works perfectly fine and if I can get dialog content from the existing input like this: 这工作得很好,如果我可以从现有输入中获取对话框内容,如下所示:

<input id="dialog-input" type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" \>
dialog = $( '#dialog-input' ).dialog({ });

However, if rendered the input directly as a jQuery object for the dialog like this, the second regex replace seems to fail getting the capturing group and something happens where it will only allow a single character in the input: 但是,如果像这样将输入直接呈现为对话框的jQuery对象,则第二个正则表达式替换似乎无法获取捕获组,并且发生了某些事情,该情况仅允许输入中包含单个字符:

dialog = $( '<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, \'\').replace(/(\..*)\./g, \'$1\');" \>' ).dialog({ });

Why does this work in one case but fail in the other? 为什么这在一种情况下有效,而在另一种情况下却失败? I have a hunch that some part of my regex needs to be escaped but I've tried a multitude of variations and nothing seems to work. 我有一种预感,我的正则表达式的某些部分需要转义,但是我尝试了多种变体,但似乎没有任何效果。

Double escape your period in the second regex: 在第二个正则表达式中两次转义您的句号:

'...replace(/(\\..*)\\./g, \'$1\');" \>'

I would just avoid working with strings: 我只是避免使用字符串:

$('<input type="text">').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
}).appendTo('body').dialog();

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

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