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

查看:33
本文介绍了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 规则和属性.有没有什么技巧可以转义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天全站免登陆