我想做这样的事情:

function alrtHtml() {
  alert(this.innerHTML)
}

function myFunc(id) {
  document.getElementById(id).alrtHtml()
}
<html>
<head>
  <meta charset="UTF-8" />
  <title>test</title>
</head>
<body>
  <h1 id="h1">Hello world!</h1>
  <input type="button" value="click" onclick="myFunc('h1')" >
</body>
</html>


结果应该是带有文本“Hello world!”的警报。在h1标记内。

我的目标是无需显式将元素作为参数传递给alertHtml即可执行此操作。

最佳答案

通常,您不希望扩展 native 原型(prototype),一种不这样做就创建可链接方法的方法是,创建自己的方法来获取元素,然后像大多数库一样,创建另一个可链接方法来警告innerHTML

也许最简单的例子就是这样

function getElement(selector) {
  if (!(this instanceof getElement)) return new getElement(selector);
  this.element = document.querySelector(selector);
  return this;
}

getElement.prototype.alertHtml = function() {
  alert(this.element.innerHTML);
  return this;
}

function myFunc(id) {
  getElement(id).alertHtml();
}

myFunc('#test');
<div id="test">TEST</div>


这样,您仅扩展自己的对象,而不扩展 native 对象,并且可以创建任何类型的可链接方法来添加该对象。

09-25 18:14
查看更多