添加js方法

发布于 2024-10-09 20:20:08 字数 788 浏览 3 评论 0原文

我有一个名为 getID 的 js 函数,它基本上是返回 document.getElementById(id)

我想创建另一个函数 getTag,它将返回 getElementsByTagName

我似乎无法管理的部分是我希望能够像这样调用它们:

getID('myid').getTag('input') =>;所以这将返回 id 为 myid 的元素内的所有输入元素,

谢谢!

ps:如果 getTag 是由它自己调用的,那么它也必须工作,但它只会返回 document.getElementsByTagName

更新:

感谢所有回复!根据你的建议,我想出了这个,这对我来说很有效:

function getEl(){
    return new getElement();
}

function getElement() {
    var scope = document;

    this.by = function(data){
        if (data.id)    scope = scope.getElementById(data.id);
        if (data.tag)   scope = scope.getElementsByTagName(data.tag);

        return scope;
    }
}

我这样使用它:

var inputs = getEl().by({id:"msg", tag:"input"});

I have a js function that is named getID which is basically return document.getElementById(id)

I want to make another function, getTag that would return getElementsByTagName.

The part that I can't seem to manage is that I want to be able to call them like this:

getID('myid').getTag('input') => so this would return all the input elements inside the element with the id myid

Thanks!

ps: getTag would also have to work if it's called by it's own, but then it would just return document.getElementsByTagName

UPDATE:

Thanks to all that have replied! Using your suggestions I came up with this, which works well for me:

function getEl(){
    return new getElement();
}

function getElement() {
    var scope = document;

    this.by = function(data){
        if (data.id)    scope = scope.getElementById(data.id);
        if (data.tag)   scope = scope.getElementsByTagName(data.tag);

        return scope;
    }
}

and I use it like this:

var inputs = getEl().by({id:"msg", tag:"input"});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

转瞬即逝 2024-10-16 20:20:08

实现这一点的方法是创建对象原型。为此,您需要以下代码:

Object.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

但是,这将展开所有对象,因为您真正需要原型化的 HTMLElement 很难一致地完成。所有专家都同意您应该永远不要扩展对象原型 。更好的解决方案是创建一个从另一个参数获取标签名称的函数:

function getTag(tagName, element) {
    return (element || document).getElementsByTagName(tagName);
}

// Usage
var oneTag = getTag('input', getID('myid')); // All inputs tags from within the myid element
var twoTag = getTag('input'); // All inputs on the page

The way to do that is to prototype Object. To do that, you'll need the following piece of code:

Object.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

However, this will expand all objects because what you really need to prototype, an HTMLElement, is very hard to do consistently. All the experts agree that you should never expand the Object prototype. A much better solution would be to create a function that gets the tag name from another argument:

function getTag(tagName, element) {
    return (element || document).getElementsByTagName(tagName);
}

// Usage
var oneTag = getTag('input', getID('myid')); // All inputs tags from within the myid element
var twoTag = getTag('input'); // All inputs on the page
小…红帽 2024-10-16 20:20:08

这要求 getID('myid')(HTML 元素)返回的任何内容都公开名为 getTag() 的方法。事实并非如此。浏览器实现 DOM 规范并公开其中定义的方法。

虽然从技术上讲您可以使用自己的方法增强本机对象,但最好不要这样做。

您尝试做的事情已经在 jQuery 等 JS 库中得到了相当好的解决,我建议您在花时间模仿它们可以做什么之前先看看其中一个。例如,您的代码行将变为:

$("#myid input")

在 jQuery 中。 jQuery 恰好是使用最广泛的 JS 库,还有很多其他库。

This would require that whatever is returned by getID('myid') (an HTML element) exposes a method named getTag(). This is not the case. Browsers implement the DOM specification and expose the methods defined there.

While you technically can enhance native objects with your own methods, it's best not to do it.

What you try to do has been solved rather nicely in JS libraries like jQuery already, I recommend you look at one of them before you invest time in mimicking what they can do. For example, your line of code would become:

$("#myid input")

in jQuery. jQuery happens to be the most widely used JS library around, there are many others.

望她远 2024-10-16 20:20:08

基本上,您将创建一个包含每个方法的单个对象,并存储本机函数返回的所有数据。它看起来像这样(未经测试,但您明白了):

var MyLib = {
    getID: function(id) {
        var element = document.getElementById(id);
        this.length = 1;
        this[0] = element;
        return this;
    },
    getTag: function(tag) {
        var elements;
        if (this.length) {
            for (var i = 0; i < this.length; i++) {
                var byTag = this[i].getElementsByTagName(tag);
                for (var j = 0; j < byTag.length; j++) {
                    elements.push(byTag[j]);
                }
            }
        }
        for (var i = 0; i < elements.length; i++) {
            this[i] = elements[i];
        }
        this.length = elements.length;
        return this;
    }
};

然后您可以像这样使用它:

var elements = MyLib.getID('myid').getTag('input');
for (var i = 0; i < elements.length; i++)
    console.log(elements[i]); // Do something

这种方法的唯一真正问题(除了它非常棘手且难以调试)是您必须处理每个方法的结果就像一个数组,即使只有一个结果。例如,要通过 ID 获取元素,您必须执行 MyLib.getID('myid')[0]

但请注意,之前已经这样做过。我建议您看看 jQuery,看看他们是如何实现这一点的。您的代码可以简化为:

$("#myid input")

jQuery 比您想象的更轻量级,将其包含在您的页面上不会减慢速度。使用它您不会有任何损失。

Basically, you're going to create a single object that contains each of your methods and also stores all data returned by the native functions. It would look something like this (not tested, but you get the idea):

var MyLib = {
    getID: function(id) {
        var element = document.getElementById(id);
        this.length = 1;
        this[0] = element;
        return this;
    },
    getTag: function(tag) {
        var elements;
        if (this.length) {
            for (var i = 0; i < this.length; i++) {
                var byTag = this[i].getElementsByTagName(tag);
                for (var j = 0; j < byTag.length; j++) {
                    elements.push(byTag[j]);
                }
            }
        }
        for (var i = 0; i < elements.length; i++) {
            this[i] = elements[i];
        }
        this.length = elements.length;
        return this;
    }
};

You can then use it like this:

var elements = MyLib.getID('myid').getTag('input');
for (var i = 0; i < elements.length; i++)
    console.log(elements[i]); // Do something

The only real problem with this approach (besides it being very tricky and hard to debug) is that you have to treat the result of every method like an array, even if there is only a single result. For example, to get an element by ID, you'd have to do MyLib.getID('myid')[0].

However, note that this has already been done before. I recommend you take a look at jQuery, if only to see how they accomplished this. Your code could be simplified to this:

$("#myid input")

jQuery is more lightweight than you think, and including it on your page will not slow it down. You have nothing to lose by using it.

So要识趣 2024-10-16 20:20:08

只需使用 DOMElement.prototype 属性即可。

你会得到类似这样的结果:

function getTag(tagName) {
    return document.getElementsByTagName(tagName);
}
DOMElement.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

但是你应该使用 jQuery。

编辑:我的解决方案不适用于 IE,抱歉!

Just use the DOMElement.prototype property.

You'll get something like this :

function getTag(tagName) {
    return document.getElementsByTagName(tagName);
}
DOMElement.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

But you should use jQuery for this.

EDIT: My solution doesn't work on IE, sorry !

巾帼英雄 2024-10-16 20:20:08

您可以按如下方式定义它:

var Result = function(el)
{
  this.Element = el;
};

Result.prototype.getTag = function(tagName)
{
  return this.Element.getElementsByTagName(tagName);
};

var getTag = function(tagName)
{
  return document.getElementsByTagName(tagName);
};

var getID = function(id)
{
  var el = document.getElementById(id);
  return new Result(el);
};

调用 getID 将返回 Result 的实例,然后您可以使用其 Element 属性来访问返回 HTML 元素。 Result 对象有一个名为 getTag 的方法,它将返回父结果中与该标记匹配的所有子元素。然后,我们还定义一个单独的 getTag 方法,该方法调用文档元素的 getElementsByTagName

尽管如此...JQuery 更容易... $("#myId input");

You could define it as follows:

var Result = function(el)
{
  this.Element = el;
};

Result.prototype.getTag = function(tagName)
{
  return this.Element.getElementsByTagName(tagName);
};

var getTag = function(tagName)
{
  return document.getElementsByTagName(tagName);
};

var getID = function(id)
{
  var el = document.getElementById(id);
  return new Result(el);
};

Whereby a call to getID will return an instance of Result, you can then use its Element property to access the HTML element returned. The Result object has a method called getTag which will return all child elements matching that tag from the parent result. We then also define a seperate getTag method which calls the document element's getElementsByTagName.

Still though...JQuery is so much easier... $("#myId input");

鱼窥荷 2024-10-16 20:20:08

除非这是一个关于如何在 JavaScript 中链接方法的学术练习(似乎不是,你似乎只是在学习 JavaScript),否则你所要做的就是:

var elements = document.getElementById("someIdName");
var elementsByTag = elements.getElementsByTagName("someTagName");
for (i=0; i< elementsByTag.length; i++) {
    alert('found an element');
}

如果你想定义一个可重用的函数,你所拥有的一切要做的是:

function myFunction(idName,tagName) {
    var elements = document.getElementById(idName);
    var elementsByTag = elements.getElementsByTagName(tagName);
    for (i=0; i< elementsByTag.length; i++) {
        alert('found a ' + tagName + ' element within element of id ' + idName);
    }
}

确实,如果这是您页面上需要的所有 JavaScript 功能,那么就不需要导入 jQuery。

Unless this is an academic exercise on how to chain methods in JavaScript (it doesn't seem to be, you simply seem to be learning JavaScript), all you have to do is this:

var elements = document.getElementById("someIdName");
var elementsByTag = elements.getElementsByTagName("someTagName");
for (i=0; i< elementsByTag.length; i++) {
    alert('found an element');
}

If you want to define a reusable function all you have to do is this:

function myFunction(idName,tagName) {
    var elements = document.getElementById(idName);
    var elementsByTag = elements.getElementsByTagName(tagName);
    for (i=0; i< elementsByTag.length; i++) {
        alert('found a ' + tagName + ' element within element of id ' + idName);
    }
}

It's true that if this is all the JavaScript functionality you need on your page, then there is no need to import jQuery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文