我编写了一个小的纯javascript库来替换JQuery(保持语法与JQuery相同,但代码是javascript)。当我将事件对象传递给它时,我正努力让.on函数正常工作,因为事件没有被传回(如果我想防止冒泡)。
第一组代码是我的库:
(function () {
var Q = function (params) {
return new Library(params);
};
var Library = function (params) {
if (typeof params === 'string') {
var selector = document.querySelectorAll(params),
counter;
this.length = selector.length;
// Add selector to object for method chaining
for (counter = 0; counter < this.length; counter++) {
this[counter] = selector[counter];
}
} else {
this.length = 1;
this[0] = params;
}
// Return as object
return this;
};
Q.fn = Library.prototype = {
/*
Name addClass()
Description Adds a class to the objects
Input className TEXT
Language Javascript
*/
addClass: function (classNames) {
var arr = classNames.split(' '),
total = arr.length,
counter,
count;
for (counter = 0; counter < this.length; counter++) {
for (count = 0; count < total; count++) {
if (!this[counter].classList.contains(arr[count])) {
this[counter].classList.add(arr[count]);
}
}
}
// Return this to allow chained methods
return this;
},
on: function (events) {
var arr = events.split(' '),
total = arr.length,
counter,
count;
if (arguments.length === 2) {
// .on('change', function(e) { ... });
for (counter = 0; counter < this.length; counter++) {
for (count = 0; count < total; count++) {
this[counter].addEventListener(arr[count], arguments[1], false);
}
}
} else {
// .on('change', 'input', function(e) { ... });
var doc = document,
selector = arguments[1],
func = arguments[2],
counter;
for (counter = 0; counter < this.length; counter++) {
var obj = this[counter];
if (isset(obj)) {
for (count = 0; count < total; count++) {
doc.addEventListener(arr[count], function() {
if (arguments[0].target.matches(obj.tagName + ' ' + selector)) {
func.call(arguments[0].target, arguments[0]);
}
}, false);
}
}
}
}
// Return this to allow chained methods
return this;
},
};
// Assign our Q object to global window object.
if (!window.Q) {
window.Q = Q;
}
})();
当我在我的代码中使用以下内容时,一切正常,但返回的事件不包含更新的属性:
Q(obj).on('click', 'a', function(e) {
e.stopPropagation();
});
我很乐意分享更多信息,我提前感谢您的帮助。
答案 0 :(得分:0)
如果我正在读取正确的代码,那是因为当你调用回调
时func.call(arguments[0].target, arguments[0]);
您没有传递活动