javascript添加onclick不成功

标签 javascript html

我的脚本:

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/

相关文章:

javascript - 无法使用 HTML 和 JavaScript 显示完整图像绘制 Canvas

java - 浏览器不会显示 HTML 文件

javascript - 无法弄清楚为什么它不起作用。 javascript调用数据键

javascript - 如何在网站的菜单页面上添加 3d Logo ?

css - zurb foundation 3 中 div 中的滚动条

javascript - 如何在 Quintus.js 中创建带标签的 Sprite ?

javascript - 滚动列表不工作

javascript - 如何等到 Javascript forEach 循环完成后再继续下一个九月

javascript - AWS Cognito 身份 NotAuthorizedException

javascript - 如何激活另一个 html 文件中的链接?