【问题标题】:How to make a function to go after an element [duplicate]如何使函数跟踪元素[重复]
【发布时间】:2016-12-03 07:58:49
【问题描述】:

JavaScript 中,您经常会看到显示document.getElementById("element").someFunction();$("element").someFunction(); 而不是someFunction($("element")); 的函数。其中someFunction(element) 看起来有点像下面的代码。

someFunction(element) {
    //element.doSomething();
}

我的问题是如何创建一个函数来操纵它所附加的元素,而不是操纵作为参数传递的元素?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

你可以使用prototype实现它

// `getElementById` returns a `Element` object so extend it's prototype
Element.prototype.someFunction = function(){
   // this.somethig
}

document.getElementById("element").someFunction();

Element.prototype.someFunction = function() {
  console.log(this.value)
}

document.getElementById("element").someFunction();
<input value="abc" id="element" />

注意:It's really bad practice to extend prototype of native object.

【讨论】:

  • 另外值得注意的是,一般不推荐扩展内置对象的原型。
  • @Seth 你会推荐我做什么?将其保留为someFunction(element) 更好吗?
  • @Dan 使用someFunction(element) ..... 仅将prototype 用于forEach, find, some, etc... 等新方法的polyfil 选项.....
【解决方案2】:

您正在寻找prototypes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

element.prototype.someFunction = function(){
  this.doSomething(); // this refers to element
}

【讨论】:

  • 这个函数只对这个元素起作用
猜你喜欢
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
相关资源
最近更新 更多