如何使用JavaScript获取具有email属性的所有跨度的内容

Tom*_*Tom 2 javascript

我想查找具有"email"属性的文档中的所有跨度,然后对于每个电子邮件地址,如果电子邮件被批准,我将检查我的服务器并向span内容注入一个带有"是"或""的img没有".我不需要PHP方面的实现,只需要JavaScript.

所以说"newsletter@zend.com"在我的数据库中被批准,HTML代码是:

<span dir="ltr"><span class="yP" email="newsletter@zend.com">Zend Technologies</span></span>
Run Code Online (Sandbox Code Playgroud)

然后,JavaScript会将HTML更改为:

<span dir="ltr"><span class="yP" email="newsletter@zend.com"><img src="yes.gif" />Zend Technologies</span></span>
Run Code Online (Sandbox Code Playgroud)

我需要有人指导我如何处理这个问题.

注意:我不想使用jQuery.

T.J*_*der 6

如果您不想使用库,并且您不希望将自己限制为支持的浏览器querySelectorAll,那么您可能最好使用简单的递归下降函数或getElementsByTagName.这是一个RD示例:

功能(袖口,未经测试):

function findEmailSpans(container, callback) {
    var node, emailAttr;
    for (node = container.firstChild; node; node = node.nextSibling) {
        if (node.nodeType === 1 && node.tagName === "SPAN") { // 1 = Element
                emailAttr = node.getAttribute("email");
                if (emailAttr) {
                    callback(node, emailAttr);
                }
            }
        }
        switch (node.nodeType) {
            case 1:  // Element
            case 9:  // Document
            case 11: // DocumentFragment
                findEmailSpans(node, callback);
                break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

打电话给:

findEmailSpans(document.documentElement, function(span, emailAttr) {
    // Do something with `span` and `emailAttr`
});
Run Code Online (Sandbox Code Playgroud)

另外,如果你想依靠getElementsByTagName(这是相当广泛的支持),而且不介意建设这么大的NodeList内存,这将是简单,可能会更快:这将让你得到一个平坦的NodeList所有的span元素,这样,那么你只是有一个简单的循环而不是递归下降函数(不是RD函数既困难又慢,但仍然如此).像这样的东西:

var spans = document.getElementsByTagName("span"),
    index, node, emailAttr;
for (index = 0; index < spans.length; ++index) {
    node = spans.item(index);
    emailAttr = node.getAttribute("email");
    if (emailAttr) {
        // Do something with `node` and `emailAttr`
    }
}
Run Code Online (Sandbox Code Playgroud)

你想要比较和决定哪种方法最适合你,每种方法都有利有弊.

参考文献:


但是,对于这种事情,我真的建议使用一个好的JavaScript库,如jQuery,Prototype,YUI,Closure其他任何一个.有了任何好的库,它看起来像这样(jQuery):

$("span[email]").each(function() {
    // Here, `this` refers to the span that has an email attribute
});
Run Code Online (Sandbox Code Playgroud)

......或者这个(原型):

$$("span[email]").each(function() {
    // Here, `this` refers to the span that has an email attribute
});
Run Code Online (Sandbox Code Playgroud)

......而其他人则不会更加复杂.使用库来考虑我们的常见操作,例如在DOM中搜索事物,可以让您专注于您尝试解决的实际问题.jQuery和(最新版本的)Prototype都会遵循querySelectorAll支持它的浏览器(我想其他大多数人也会这样),并且在没有的浏览器上回退到他们自己的搜索功能.