遇到一个奇怪的错误——所以我在我的 HTML 中的 button
元素上有一个定义为“data-tagtype”的属性。当用户单击按钮时,将调用以下方法:
onClickTag: function(e) {
if (!this.playerLoaded) {
return false;
}
var type = $(e.target).data('tagtype');
var seconds = this.getCurrentTime();
console.log(type);
if (type) {
this.model.addTag({
type: type,
seconds: seconds
});
}
},
这在大多数 时间都有效,但由于某些原因,有时type
未定义(看似)随机元素。相应的 HTML 在这里:
<button id="tag-love" class="tagger disabled" data-tagtype="love"><i class="fa fa-heart fa-fw"></i></button>
<button id="tag-important" class="tagger disabled" data-tagtype="important"><i class="fa fa-exclamation fa-fw"></i> Important</button>
<button id="tag-more" class="tagger disabled" data-tagtype="more"><i class="fa fa-ellipsis-h fa-fw"></i> More</button>
<button id="tag-confused" class="tagger disabled" data-tagtype="confused"><i class="fa fa-question fa-fw"></i> Confused</button>
这很奇怪,因为似乎没有关于哪些返回 undefined 的模式。有时它们全部工作,有时其中一个会返回 undefined 几秒钟,但如果我继续单击它会返回正确的值。
在调用任何这些方法之前, View 肯定会被渲染/加载到 DOM 中。
有什么想法吗? Backbone 会做些什么吗?
最佳答案
问题在于 Backbone View 使用事件委托(delegate)来处理事件。这意味着 e.target
将是被单击的元素,而不是响应事件的元素。如果您单击 <i>
, e.target
会是<i>
但是如果你点击文本,e.target
将是 <button>
; <i>
没有您要查找的数据属性,但有 <button>
做。这意味着有时 $(e.target).data('tagtype')
将是 undefined
.
您可以在一个简单示例中看到此行为:
<div id="x">
<button type="button" data-tagtype="love"><i>icon</i> text</button>
</div>
和最小 View :
var V = Backbone.View.extend({
el: '#x',
events: {
'click button': 'clicked'
},
clicked: function(ev) {
console.log(
$(ev.target).data('tagtype'),
$(ev.currentTarget).data('tagtype')
);
}
});
演示:http://jsfiddle.net/ambiguous/pe77p/
如果您点击 <i>icon</i>
,你会得到 undefined love
在控制台中,但如果您单击 text
,你会得到 love love
在控制台中。
那个小演示还包含解决方案:使用 e.currentTarget
而不是 e.target
.
关于javascript - jQuery 数据 $(...).data ('foo' ) 有时会在 Backbone 应用程序中返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079847/