我正在使用javascript。我想在javascript中继承Common对象和其他对象。有可能吗?我的意思是将这个js转换为原型模型。
function setEvent(evt, ele, callback) {
var ele = getEle(ele);
if (ele.length === undefined) {
ele.addEventListener(evt, callback, false);
} else if (ele.length > 0) {
for (var i = 0; i < ele.length; i++) {
ele[i].addEventListener(evt, callback, false);
}
}
return false;
}
function getEle(ele) {
var _idf = ele.charAt(0);
if (_idf == "#") {
var _ele = document.getElementById(ele.substr(1));
return _ele;
} else if (_idf == ".") {
var _els = document.getElementsByClassName(ele.substr(1));
return _els;
}
return ele;
}
function getInnerHtml(id) {
return document.getElementById(id).innerHTML;
}
function getValue(elem) {
return elem.value;
}
setEvent("click", ".input", function() {
console.log(this.value);
var _num = getInnerHtml("math");
_num = _num + "" + getValue(this);
document.getElementById("math").innerHTML = _num;
});
答案 0 :(得分:0)
要了解您正在尝试构建的对象模型类型有点难,因为您没有描述这方面的任何要求或愿望。这里有一个像jQuery这样的工作的想法:
function core(selector) {
if (!(this instanceof core)) {
return new core(selector);
}
var items = document.querySelectorAll(selector);
if (items) {
this.items = Array.prototype.slice.call(items);
} else {
this.items = [];
}
this.length = this.items.length;
return this;
}
core.prototype = {
each: function(fn) {
for (var i = 0; i < this.length; i++) {
fn.call(this.items[i]);
}
return this;
},
firstProp: function(propName, defaultVal) {
if (this.length > 0) {
var val = this.items[0][propName];
return val !== undefined ? val : defaultVal;
} else {
return defaultVal;
}
},
getHTML: function() {
return this.firstProp("innerHTML", "");
},
setHTML: function(html) {
return this.each(function() {
this.innerHTML = html;
});
},
on: function(event, fn) {
return this.each(function() {
this.addEventListener(event, fn);
});
},
getValue: function() {
return this.firstProp("value", "");
}
};
然后,像你这样的用法示例:
core(".input").on("click", function(e) {
console.log(this.value);
var math = core("#math");
math.setHTML(math.getHTML() + this.value);
});