我想做这样的事情:
function alrtHtml() {
alert(this.innerHTML)
}
function myFunc(id) {
document.getElementById(id).alrtHtml()
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
结果应该是带有文本“Hello world!”的警报。内部h1标签。
我的目标是能够在不显式将元素作为参数传递给alertHtml.
您通常不想扩展本机原型,并且在不这样做的情况下创建可链接方法的一种方法是创建您自己的方法来获取元素,然后创建另一个可链接方法来警告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');Run Code Online (Sandbox Code Playgroud)
<div id="test">TEST</div>Run Code Online (Sandbox Code Playgroud)
这样,您只扩展自己的对象,而不是本机对象,并且您可以创建任何类型的可链接方法来添加它。
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |