我有这个小提琴https://jsfiddle.net/3azcbye3/2/,它显示了我遇到过的确切场景。
我想知道为什么当我执行$('[data-prototype]').each
时,我无法使用$(this).data('prototype', value)
更新数据属性,而是需要使用$(this).attr('data-prototype', value)
。
当click事件稍后用.data('prototype')
抓取原型时,就好像它抓取DOM值而不是应该在jQuery局部变量中更新的值。据我了解.attr
vs .data
,我原本预计两者之间会出现反比。
编辑:在小提琴中实现事件片段的简化版本后,它似乎按预期工作。我的其他库中必定存在导致冲突的内容。
答案 0 :(得分:2)
两个代码都返回相同的结果
这:
$('[data-prototype]').each(function(i, element) {
var prototype = $($(element).data('prototype'));
prototype.find('label').each(function(l, label) {
$(label).text('****'); //removed code for clarity
});
$(this).data('prototype', prototype[0].outerHTML);
console.log( $(this).data('prototype'))
});
收益率:
<div class="form-group"><label class="control-label required">****</label><div id="ew_ability_attributeComponents___name__"><div class="form-group"><label class="control-label" for="ew_ability_attributeComponents___name___attribute">****</label><select id="ew_ability_attributeComponents___name___attribute" name="ew_ability[attributeComponents][__name__][attribute]" class="form-control"><option value=""></option><option value="1">Reflexes</option></select></div><div class="form-group"><label class="control-label required" for="ew_ability_attributeComponents___name___composition">****</label><div class="input-group"><input type="text" id="ew_ability_attributeComponents___name___composition" name="ew_ability[attributeComponents][__name__][composition]" required="required" class="form-control"><span class="input-group-addon">%</span>
</div></div></div></div>
这段代码:
$('[data-prototype]').each(function(i, element) {
var prototype = $($(element).data('prototype'));
prototype.find('label').each(function(l, label) {
$(label).text('****');
});
$(this).attr('data-prototype', prototype[0].outerHTML);
console.log( $(this).attr('data-prototype'))
});
收益率:
<div class="form-group"><label class="control-label required">****</label><div id="ew_ability_attributeComponents___name__"><div class="form-group"><label class="control-label" for="ew_ability_attributeComponents___name___attribute">****</label><select id="ew_ability_attributeComponents___name___attribute" name="ew_ability[attributeComponents][__name__][attribute]" class="form-control"><option value=""></option><option value="1">Reflexes</option></select></div><div class="form-group"><label class="control-label required" for="ew_ability_attributeComponents___name___composition">****</label><div class="input-group"><input type="text" id="ew_ability_attributeComponents___name___composition" name="ew_ability[attributeComponents][__name__][composition]" required="required" class="form-control"><span class="input-group-addon">%</span>
</div></div></div></div>
将结果带到无法比较,两者都是相同的: