小部件需要通过创建元素并将它们附加到this.element来对鼠标事件做出反应.
如果窗口小部件应用于HTML元素(例如不能包含子元素的IMG标记),则窗口小部件将创建代理包装元素并包装this.element.
如果我用包装元素替换this.element,那么小部件触发的事件永远不会被处理,因为小部件实例上的.bind()调用将处理程序应用于原始元素,而不是包装器.
如果我不用包装元素替换this.element,则ui.mouse定义的_mouse *事件不会被正确调用,因为它们应用于this.element而不是包装器.
是否有一种优雅的方式以某种方式返回包装元素,以便后续的bind()调用应用于它或使ui.mouse原型应用于除this.element之外的元素?
任何其他优雅的解决方案或建议将非常受欢迎.
这些是我尝试过的两个场景.
不替换this.element
$.widget("ui.example", ui.mouse, {
_containerElement: null,
_create: function ()
{
if (this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i))
{
this._applyContainer();
}else{
this._containerElement = this.element;
}
// Applies mouse interaction handlers to this.element
this._mouseInit();
},
_applyContainer: function ()
{
this.element.wrap("<span>");
this._containerElement = this.element.parent();
this._containerElement.css({position:'relative'});
},
_mouseStart: function (event) {
// Not always called because it handles mouse interaction with
// the IMG element rather than the wrapper element
this._trigger("mouseevent");
}
})
$("IMG").example().bind("examplemouseevent", function(){
//This fires but only when the original IMG element is clicked, not the wrapper
})
替换this.element
$.widget("ui.example", ui.mouse, {
_create: function ()
{
if (this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i))
{
this._applyContainer();
}
// Applies mouse interaction handlers to this.element
this._mouseInit();
},
_applyContainer: function ()
{
this.element.wrap("<span>");
this.element = this.element.parent();
this.element.css({position:'relative'});
},
_mouseStart: function (event) {
// This event is never handled because it is not raised on the original element.
this._trigger("mouseevent");
}
})
$("IMG").example().bind("examplemouseevent", function(){
//This never fires because the bind is to the IMG element, not the wrapper
})
我很确定我遇到的问题是由于我理解jquery ui.mouse工作方式的缺点,或者jquery小部件框架的限制.
使用包装原始this.element的元素替换this.element,但事件不会传递给稍后绑定到窗口小部件的处理程序.
不替换this.element并将单独的引用存储到包装器会导致jquery base ui.mouse的行为将事件附加到错误的元素.
我可以看到许多解决这个问题的方法.例如;使用_trigger方法对正确的元素触发事件或者在ui.mouse附加所需的处理程序时向后和向前交换this.element值.
我考虑过的这些和任何其他方法看起来都很混乱.
我查看了本机jquery.resizable小部件代码,它也创建了一个包装器,但据我所知,如果它试图触发事件,它也会遇到同样的问题.
这是我第一次使用JQuery小部件,所以我想从JQuery大师那里确认一下,我不缺少什么东西?
解决方法:
我会尝试一种方法:
_applyContainer: function ()
{
this.element.wrap("<span>");
this.element.bind("list of events", function(){
this.element.parent().trigger("name of event");
});
this.element = this.element.parent();
this.element.css({position:'relative'});
}
构建包装器元素时,绑定子项,无论事件列表如何(如果此概念不起作用,您可以迭代)并触发父(范围,已知)元素同名事件.
注意:“事件列表”应该类似于“鼠标悬停点击”等,然后应该用一些逻辑替换“事件名称”以检测哪些列表被触发.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。