与jQuery或Javascript在页面上选择号码 [英] Select numbers on a page with jQuery or Javascript

查看:149
本文介绍了与jQuery或Javascript在页面上选择号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有与jQuery的或纯JavaScript的网页上找到号码的方式。

I'm just wondering if there's a way to locate numbers on a page with jQuery or plain Javascript.

这就是我想要做的:

说6月23日,是在页面上。我想要做的是能prePEND有的&LT追加;跨度> 选择的号码。

Say "June 23" is on the page. What I want to do is be able to prepend and append some <span> selectors to the number.

使用:包含()与jQuery选择了整个事情,而不仅仅是数量。

Using :contains() with jQuery selects the whole thing, not just the number.

这些字符串被未经一句话preSS主题的包裹件我正在生成,我只想选择数字

These strings are being generated without any wrapping elements by a Wordpress theme I'm working on, and I only want to select the number.

任何帮助将是AP preciated!感谢您甚至想着它。
结果
-George

Any help would be appreciated! Thanks for even thinking about it.
-George

推荐答案

您可以通过所有的元素散步,看着文本节点,并与更新后的内容已经数包裹替换它们。

You can walk through all the elements, looking at text nodes, and replacing them with updated content that has the number wrapped.

var regex = /(\d+)/,
    replacement = '<span>$1</span>';

function replaceText(el) {
    if (el.nodeType === 3) {
        if (regex.test(el.data)) {
            var temp_div = document.createElement('div');
            temp_div.innerHTML = el.data.replace(regex, replacement);
            var nodes = temp_div.childNodes;
            while (nodes[0]) {
                el.parentNode.insertBefore(nodes[0],el);
            }
            el.parentNode.removeChild(el);
        }
    } else if (el.nodeType === 1) {
        for (var i = 0; i < el.childNodes.length; i++) {
            replaceText(el.childNodes[i]);
        }
    }
}

replaceText(document.body);

示例: http://jsfiddle.net/JVsM4/

这不会做现有元素,及其相关的jQuery数据造成任何损坏。

This doesn't do any damage to existing elements, and their associated jQuery data.

编辑::您可以缩短一点用一点jQuery的:

You could shorten it a bit with a little jQuery:

var regex = /(\d+)/g,
    replacement = '<span>$1</span>';

function replaceText(i,el) {
    if (el.nodeType === 3) {
        if (regex.test(el.data)) {
            $(el).replaceWith(el.data.replace(regex, replacement));
        }
    } else {
        $(el).contents().each( replaceText );
    }
}

$('body').each( replaceText );

示例: http://jsfiddle.net/JVsM4/1/

请注意,正则表达式要求先按g 全球改性剂。

Note that the regex requires the g global modifier.

可能有点这种方式,所以如果DOM是相当大的,我会使用非jQuery的版本。

Probably a little slower this way, so if the DOM is quite large, I'd use the non-jQuery version.

这篇关于与jQuery或Javascript在页面上选择号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆