使用 LiveValidation 构造函数替换 eval()

发布于 2024-08-15 05:25:52 字数 625 浏览 2 评论 0原文

我正在使用 LiveValidation 作为输入元素。这些来自通过 AJAX 调用检索的表,并且可以是 4 的倍数,介于 4 和 36 之间的任何位置。

我使用 eval 调用 LiveValidation 的构造函数,因为输入元素的数量在每次 AJAX 调用后可能会有所不同,并且我无法想不出另一种方法(我对 JavaScript 没有太多经验)。

我正在使用这个:

$("input[type=text]", tableElement).each(function(index) {
    eval("var temp_" + index + " = new LiveValidation(this, { wait: 0, validMessage: ' ' });");
    eval("temp_" + index + ".add(Validate.Numericality, { onlyInteger: true });");
    eval("temp_" + index + ".add(Validate.Presence, { failureMessage: 'Cannot be blank' });");
});

在不使用 eval 的情况下实现相同目标的更好方法是什么,因为我知道应该非常谨慎地使用它。

I'm using LiveValidation for input elements. These come in a table retrieved with an AJAX call, and can be multiples of 4, anywhere between 4 and 36.

I'm using eval to call the constructor for LiveValidation as the number of input elements can vary after each AJAX call and I couldn't think of another way (I don't have much experience with JavaScript).

I'm using this:

$("input[type=text]", tableElement).each(function(index) {
    eval("var temp_" + index + " = new LiveValidation(this, { wait: 0, validMessage: ' ' });");
    eval("temp_" + index + ".add(Validate.Numericality, { onlyInteger: true });");
    eval("temp_" + index + ".add(Validate.Presence, { failureMessage: 'Cannot be blank' });");
});

What would be a better way of doing achieving the same without the use of eval as I know it should be used very sparingly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉宸 2024-08-22 05:25:52

好吧,看来我可以用这个:

$("input[type=text]", tableElement).each(function(index) {
    var temp = new LiveValidation(this, { wait: 0, validMessage: ' ' });
    temp.add(Validate.Numericality, { onlyInteger: true });
    temp.add(Validate.Presence, { failureMessage: 'Cannot be blank' });
});

我以为那行不通,但它确实有效。

Well, seems like I can just use this:

$("input[type=text]", tableElement).each(function(index) {
    var temp = new LiveValidation(this, { wait: 0, validMessage: ' ' });
    temp.add(Validate.Numericality, { onlyInteger: true });
    temp.add(Validate.Presence, { failureMessage: 'Cannot be blank' });
});

I thought that that wouldn't work, but it does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文