jQuery Nice Number微调器仅对指定类应用0.1步进逻辑的实现问题
实现方案
你原有代码的核心问题是将if判断直接写在了niceNumber()方法的配置对象内部,不符合JavaScript语法规范,因此自定义步进逻辑无法按预期生效。可按以下两种方式修改实现需求:
方式一:分开初始化(更推荐,性能更好)
仅对带有ist类的数字输入框应用自定义步进规则,其余输入框走插件默认逻辑:
$(function () { // 带ist类的输入框:自定义0.1步进逻辑 $('input[type="number"].ist').niceNumber({ onDecrement: ($el, newValue, settings) => { $el.val(Math.round(newValue * 10) / 10); }, onIncrement: ($el, newValue, settings) => { $el.val(Math.round(newValue * 10) / 10); } }); // 不带ist类的输入框:使用默认配置 $('input[type="number"]:not(.ist)').niceNumber(); });
方式二:回调内判断类名
如果需要统一初始化所有输入框,可以在增减回调内判断当前元素是否带有目标类:
$(function () { $('input[type="number"]').niceNumber({ onDecrement: ($el, newValue, settings) => { if ($el.hasClass('ist')) { $el.val(Math.round(newValue * 10) / 10); } }, onIncrement: ($el, newValue, settings) => { if ($el.hasClass('ist')) { $el.val(Math.round(newValue * 10) / 10); } } }); });
注意:你原有代码里的数值计算逻辑存在偏差风险,修改后的
Math.round(newValue * 10) / 10可以保证步进值始终稳定为0.1,和输入框上设置的step="0.1"属性完全匹配。
内容的提问来源于stack exchange,提问作者nasm
相关产品推荐
相关产品推荐

