【发布时间】:2016-05-12 04:51:45
【问题描述】:
我想访问带有关键字的 javascript 对象属性:
var cloneIndex = $(".clonedInput").length + 1;
$(document).on("click", 'button.clone', function (e) {
e.preventDefault();
$(this).closest(".clonedInput").clone().insertAfter(".clonedInput:last").attr("id",
"clonedInput" + cloneIndex).find("[id], [name] ,[data-valmsg-for]").each(
function () {
this.id = this.id.replace(/\d+$/, cloneIndex);
this.name = this.name.replace(/\d/, cloneIndex);
this.data-valmsg-for = this.data-valmsg-for.replace(/\d/, cloneIndex);
});
cloneIndex++;
});
但是因为一行:
this.data-valmsg-for = this.data-valmsg-for.replace(/\d/, cloneIndex);
有:
this.data-valmsg-for
它会引发错误,因为 data-valmsg-for 中的“for”是关键字。 当我改变时:
this.data-valmsg-for
收件人:
this['data-valmsg-for'] = this['data-valmsg-for'].replace(/\d/, cloneIndex);
脚本抛出此错误:
Uncaught TypeError: Cannot read property 'replace' of undefined
当我改变时:
this.data-valmsg-for
收件人:
this.setAttribute('data-valmsg-for',this.getAttribute('data-valmsg-for').replace(/\d/, cloneIndex));
脚本抛出此错误:
Uncaught TypeError: Cannot read property 'replace' of null
这是我的html:
<div id="clonedInput1" class="form-group clonedInput">
<input id="CompanyId1" name="[0].CompanyId" type="hidden" value="">
<label class="control-label col-md-2" for="NationalCode">کد ملی</label>
<div class="col-md-3">
<input class="form-control text-box single-line" data-val="true" data-val-regex="فرمت کد ملی صحیح نمی باشد" data-val-regex-pattern="^[0-9]{10}$" @*data-val-remote="'کد ملی' is invalid." data-val-remote-additionalfields="*.NationalCode,*.initialNationalCode" data-val-remote-url="/Account/IsValidNationalCode"*@ data-val-required="وارد کردن کد ملی اجباریست" id="NationalCode1" name="[0].NationalCode" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="[0].NationalCode" data-valmsg-replace="true"></span>
</div>
<label class="control-label col-md-2" for="BirthDate">BirthDate</label>
<div class="col-md-3">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field BirthDate must be a date." data-val-required="The BirthDate field is required." id="BirthDate1" name="[0].BirthDate" type="date" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="[0].BirthDate" data-valmsg-replace="true"></span>
</div>
</div>
【问题讨论】:
-
您必须使用
[ ]表示法,并且您必须检查属性是否存在。 -
问题不在于
for。问题主要是-。this.data-valmsg-for表示this.dataminusvalmsgminusfor。 "Cannot read property 'replace' of undefined" 表示该属性不存在。如果属性只是for,那么this.for就可以正常工作。 -
鉴于
this是一个DOM 元素,您正在寻找this.getAttribute('data-valmsg-for')。 -
这被 Felix 错误地标记为重复。 OP 明确表示,在使用 [] 表示法时他仍然遇到错误。所谓的重复只是解决 [] 符号的问题。
-
Get data attribute 的副本。
标签: javascript dom