jQuery更改所有元素的文本 [英] JQuery change all elements text

查看:92
本文介绍了jQuery更改所有元素的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要jquery来更改所有页面中的数字。例如,我想将1更改为۱,所以我尝试了这种方式:

I need jquery to change numbers in all of pages. for example i want change 1 to ۱ so i tried this way:

$("*").each(function(){
    $(this).html(  $(this).html().replace(1,"۱")  );
})

,但这也会更改CSS规则和属性。

but this will change css rules and attributes also. is there any trick to escape css and attributes?

推荐答案

这不是jQuery自然适合的工作吗?而不是让jQuery获取所有元素的平面列表,而是自己递归地遍历DOM树,搜索文本节点以执行替换。

This isn't a job that jQuery naturally fits into. Instead of getting jQuery to fetch a flat list of all elements, recursively traverse through the DOM tree yourself, searching for text nodes to perform the replace on.

function recursiveReplace(node) {
    if (node.nodeType === Node.TEXT_NODE) {
        node.nodeValue = node.nodeValue.replace("1", "۱");
    } else if (node.nodeType == Node.ELEMENT_NODE) {
        $(node).contents().each(function () {
            recursiveReplace(this);
        });
    }
}

recursiveReplace(document.body);

在操作中查看此处

这篇关于jQuery更改所有元素的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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