3

这是一个更广泛的问题的一部分。它的关注度很低,所以让我问一下我自己无法实现的唯一部分。如何为 dom 对象注册类似 jquery 的 javascript 函数?假设我有以下 html 页面:

<html><body>
  <div id = "table"/>
  <div id = "chart"/>
</body></html>

并希望能够打电话$('#table').update()$('#chart').update()?我需要这些更新函数来包含不同的逻辑和局部变量,例如不同的 url 来加载数据。对不起,可能是菜鸟。

更新

如果我理解正确,插件是全局命名空间中可以处理任何对象的函数。我宁愿将不同的功能与不同的元素相关联。那是因为我认为将不同的update函数与不同的对象关联起来会更容易,而不是编写一个更新函数,每个对象都必须研究它是否适用,如果是,如何。

4

3 回答 3

6

你所追求的是jQuery 的fn.extend()

$.fn.extend({
    update: function() {
        /* Required code. */
    }
});

然后你可以简单地调用.update()一个 jQuery 对象来执行该函数:

$('myElement').update();

作为一个示例使用,如果我们想记录id一个元素的 ,我们可以将我们的update()函数定义为:

$.fn.extend({
    update: function() {
        console.log("ID = " + this.id);
    }
});

然后调用:

$('#table').update();

哪个会记录:

ID = 表

于 2013-10-28T14:06:29.087 回答
3

You don't need jQuery for this. DOM elements are objects, so you can give them any methods you want:

var table = document.getElementById('table');
table.update = function() {
  this.innerHTML += 'table updated ';
}.bind(table);

var chart = document.getElementById('chart');
chart.update = function() {
  this.innerHTML += 'chart updated ';
}.bind(chart);


document.getElementById('table').update();
document.querySelector('#chart').update();

Example: http://jsbin.com/uReyIRi/1/edit

于 2013-10-28T14:10:13.333 回答
2

您可以通过其原型向 DOM 对象添加新方法。

/* extend existing prototype */
HTMLTable.prototype.update = function() {
    console.log( this );
}

/* call new method */
document.querySelector( 'table' ).update();

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

于 2013-10-28T14:17:31.293 回答