我的脚本:
function $(attr){
if(attr.charAt(0) == "#"){
return document.getElementById(attr.substr(1));
}else{
if(attr.charAt(0) == "."){
return document.getElementsByClassName(attr.substr(1));
}else{
return document.getElementsByTagName(attr);
}
}
}
Object.prototype.onclick = function(script){
this.onclick = script;
}
$("#hi").onclick(function(){alert("hi");});
在 html 中它只是一个带有 id hi
的标签。
当我点击按钮时,没有任何反应。 我该怎么办?
最佳答案
扩展 Object
是不好的做法,我不推荐它。同样在现代浏览器中,您想做的事情相当简单,您可以使用 querySelectorAll , 并使用 addEventListener 添加事件:
// An IIFE (Immediately Invoked Function Expression)
var $ = (function() {
// Constructor
function $(selector) {
// querySelectorAll returns a pseudo-array
this.el = toArray(document.querySelectorAll(selector));
}
// Get elements as array or an element by index
$.prototype.get = function(i) {
return i == null ? this.el : this.el[i];
};
// Public method to add any event
$.prototype.on = function(event, f) {
this.el.forEach(function(el) {
el.addEventListener(event, f);
});
// chain
return this;
};
// shortcut for click event
$.prototype.click = function(f) {
return this.on('click', f);
};
// Coverts pseudo-arrays to real arrays
function toArray(x) {
return Array.prototype.slice.call(x);
}
// Wrapper to create instances
// without using the "new" keyword
return function(x) {
return new $(x);
}
}());
$('#hi').click(function(){alert('hi')});
Fiddle
关于javascript添加onclick不成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23718998/