在DOM元素上调用自定义方法 [英] Invoke a custom method on a DOM element
问题描述
我想在DOM元素上调用自定义方法
I want to invoke a custom method on a DOM element
像这样:
<div id="MyObject">
<!-- some elements -->
</div>
<script>
function doSomething() {
// do something with input DOM element
}
$("MyObject").doSomething();
</script>
如何解决这个问题?是否需要使用jQuery?
How can I develop this problem? Is it necessary to use jQuery or not?
推荐答案
您不需要使用jQuery.您可以使用 document.getElementById('MyObject')
获取对DOM节点的引用.
You do not need to use jQuery. You can use document.getElementById('MyObject')
to get a reference to the DOM node.
要在其上运行 doSomething
函数,您需要向其添加一个节点参数,如下所示:
To run your doSomething
function on it, you would need to add a node parameter to it something like this:
function doSomething(input) {
// do something with input DOM element
}
doSomething(document.getElementById('MyObject'));
要使其链接起来,您需要向所有DOM节点实现的 Element
接口添加(重读,我的意思是继承).如果您采用这种方式,则可以执行以下操作:
To have it chained, you would need to add to the Element
interface which all DOM nodes implement (rereading, I meant inherit from). If you go that way, you could do:
Element.prototype.doSomething = function() {
alert(this);
}
document.getElementById('MyObject').doSomething();
JSFiddle: http://jsfiddle.net/6Lyb4b9p/
JSFiddle: http://jsfiddle.net/6Lyb4b9p/
MDN: getElementById
这篇关于在DOM元素上调用自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!