最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if element has autoNumeric initialized - Stack Overflow

programmeradmin1浏览0评论

How to check if an HTML element already has autoNumeric initialized, so i won't initialize it again?

Initializing it twice results in all input numbers appearing twice.

if (// autonumeric not yet initialized) {
    var anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

Edit: The reason to check is that autoNumeric might be previously initialized elsewhere, in another script with different autoNumericSettings and this script needs to respect the earlier set settings.

How to check if an HTML element already has autoNumeric initialized, so i won't initialize it again?

Initializing it twice results in all input numbers appearing twice.

if (// autonumeric not yet initialized) {
    var anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

Edit: The reason to check is that autoNumeric might be previously initialized elsewhere, in another script with different autoNumericSettings and this script needs to respect the earlier set settings.

Share Improve this question edited Dec 6, 2019 at 17:07 isherwood 61.1k16 gold badges120 silver badges168 bronze badges asked Mar 7, 2018 at 12:10 lofihelsinkilofihelsinki 2,5712 gold badges27 silver badges36 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

probably, you can use getAutoNumericElement(domElement) to check if an HTML element already has autoNumeric initialized

if (AutoNumeric.getAutoNumericElement(domElement) === null) {
    var anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

You can indeed use AutoNumeric.getAutoNumericElement(domElement) as Aliaksandr mentioned to check if an element is returned, but the official way to check if a DOM element is already managed by AutoNumeric is this:

AutoNumeric.isManagedByAutoNumeric(domElementOrSelector);

So your code should be updated like so:

let anObject;
if (!AutoNumeric.isManagedByAutoNumeric(inputSel)) {
    // Also, no need to querySelector `inputSel` here:
    anObject = new AutoNumeric(inputSel, autoNumericSettings);
}

EDIT: Disclaimer; I'm the maintainer of AutoNumeric

Don't declare the variable inside the if, do it outside and then just check.

var anObject = null;

if(anObject !== null) {
   anObject = new AutoNumeric(document.querySelector(inputSel), autoNumericSettings);
}

If you post a bit more of your code I can make it better, I really don't know the structure of your complete code, but the principle is the same.

发布评论

评论列表(0)

  1. 暂无评论