转换所有数字,排除特定类

时间:2016-12-10 22:42:49

标签: javascript jquery

我可以将HTML标记中的所有数字转换为波斯数字,但我想从转换数字中排除特定的类。

我将代码更改为以下但不起作用。

DEMO: https://jsfiddle.net/o87bdzba/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
persian={0:'۰',1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹'};
	function traverse(el){
		if(el.nodeType==3){
			var list=el.data.match(/[0-9]/g);
			if(list!=null && list.length!=0){
				for(var i=0;i<list.length;i++)
					el.data=el.data.replace(list[i],persian[list[i]]);
			}
		}
		for(var i=0;i<el.childNodes.length;i++){
			traverse(el.childNodes[i]);
		}
	}
    //traverse(document.body.not('.dont_convert')); ** this 
traverse(document.body);
November <span class"dont_convert">2016</span> Community Moderator Election RESULTS
Documentation Update, November 29th

1 个答案:

答案 0 :(得分:3)

您可以检查元素是否具有“dont_convert”类。

persian={0:'۰',1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹'};
function traverse(el){
  if(el.classList && el.classList.contains('dont_convert')){
    return;
  }
  if(el.nodeType==3){
    var list=el.data.match(/[0-9]/g);
    if (list != null && list.length != 0) {
    for (var i = 0; i < list.length; i++)
      el.data = el.data.replace(list[i], persian[list[i]]);
    }
  }
  for (var i = 0; i < el.childNodes.length; i++) {
    traverse(el.childNodes[i]);
  }
}

traverse(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
November <span class="dont_convert">2016</span> Community Moderator Election RESULTS Documentation Update, November 29th

更新:JQuery版

persian={0:'۰',1:'۱',2:'۲',3:'۳',4:'۴',5:'۵',6:'۶',7:'۷',8:'۸',9:'۹'};
function traverse(el){
  if($(el).hasClass('dont_convert')){
    return;
  }
  if(el.nodeType==3){
    var list=el.data.match(/[0-9]/g);
    if (list != null && list.length != 0) {
    for (var i = 0; i < list.length; i++)
      el.data = el.data.replace(list[i], persian[list[i]]);
    }
  }
  for (var i = 0; i < el.childNodes.length; i++) {
    traverse(el.childNodes[i]);
  }
}

traverse(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
November <span class="dont_convert">2016</span> Community Moderator Election RESULTS Documentation Update, November 29th