javascript - 参数化 on() 函数 jquery
问题描述
我有不同的用户输入。当其中一个发生更改时,我只想将更改事件捕获为其值。我正在尝试自定义现有产品的代码。我的目标是在用户输入错误时弹出一个错误 div,但我当前的代码在所有输入下添加了错误 div。此代码适用于所有输入,但我希望它仅适用于具有包含“Valore”的标签父标题的输入。
JS代码:
$(document).on('focusin', 'input', function () {
$(this).data("oldvalue", this.value);
});
$(document).on('change', 'input', function () {
var $formGroup = $(this).closest('.binf-form-group');
if ($.isNumeric(this.value)) {
$formGroup.find('.binf-help-block').remove();
} else {
this.value = $(this).data("oldvalue");
$('<div class="binf-help-block" role="alert" style="white-space: normal;margin-top: 8px;background: #fff;color: #df3324;font-size: 11px;line-height: 16px;border-radius: 2px;border-left: 2px solid #df3324;padding: 0 8px;box-shadow: 0 0 4px 0 rgba(0,0,0,.3);">This value must be a number.</div>').appendTo($formGroup).fadeOut(3000, function () { $(this).remove()});
}
});
HTML:
<div class="csui-field-text alpaca-container-item" data-alpaca-container-item-index="6" data-alpaca-container-item-name="4333_35" data-alpaca-container-item-parent-field-id="alpaca44">
<div class="binf-form-group alpaca-field alpaca-field-text alpaca-required binf-has-error alpaca-invalid" data-alpaca-field-id="alpaca58">
<label class="binf-control-label alpaca-control-label binf-col-sm-3" for="alpaca58" id="alpaca58Label" title="Valore">
<span class="alpaca-icon-required binf-glyphicon binf-glyphicon-star"></span>
Valore
</label>
<div class="binf-col-sm-9">
<div class="alpaca-control">
<div id="alpaca583195" class="cs-formfield cs-textfield cs-formfield-invalid">
<div class="cs-field-write">
<div class="cs-field-write-inner">
<input type="text" id="alpaca58" maxlength="32" placeholder="Add text" value="" aria-labelledby="alpaca58Label" aria-required="true" tabindex="-1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
谢谢你的帮助!
解决方案
$(document).on('change', 'input', function () {
var title = $(this).closest(".binf-form-group").find("label").attr("title");
if(title.indexOf("Valore") >= 0){
var $formGroup = $(this).closest('.binf-form-group');
if ($.isNumeric(this.value)) {
$formGroup.find('.binf-help-block').remove();
} else {
this.value = $(this).data("oldvalue");
$('<div class="binf-help-block" role="alert" style="white-space: normal;margin-top: 8px;background: #fff;color: #df3324;font-size: 11px;line-height: 16px;border-radius: 2px;border-left: 2px solid #df3324;padding: 0 8px;box-shadow: 0 0 4px 0 rgba(0,0,0,.3);">This value must be a number.</div>').appendTo($formGroup).fadeOut(3000, function () { $(this).remove()});
}
}
});
推荐阅读
- asp.net-core - 是否有针对 ASP.NET Core 的不同引导类的指南?
- xamarin.forms - Xamarin 中的砌体列表样式
- apache-spark - Spark CSV:解析由 Ascii æ (Hex E6) 分隔的文件
- python - 即使我下载了较新版本的python,我似乎也没有 pip
- c# - 使用 Stack 机器用 Brouncer 公式逼近 PI
- laravel - 如何在 Laravel 中使用 Bulma 创建 Select2 多个值
- c++ - 未定义对“sqlite3_open”的引用。我没主意了
- java - 为什么乘法后我的乘积结果为 0
- mysql - 哪个是更好的做法:“检查主 ID 是否存在然后跳过”或“插入忽略”?
- tableau-api - 比较用户选择与两个不同的基准