2016-10-26 37 views
0

我有一个DOM这样如何找到div内的所有数字并添加<span></span>使用jquery的标签?

<div class="main_div"> 
    <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?</p>  
</div> 

我只是想span标签添加到所有号码,如

<div class="main_div"> 
    <p>A car averages <span> 27 </span> miles per gallon. If gas costs $<span>4.04</span> per gallon, which of the following is closest to how much the gas would cost for this car to travel <span>2,727</span> typical miles?</p>  
</div> 

我都试过,可能的方式和检查这个环节太

Javascript/jquery get number value inside of element

How to get number inside a div with jquery

Jquery - Adding all numbers inside span of a particular class

但这只能选择第一个数字只是我想选择div内的所有号码,如果该div包含20个号码我只需要添加跨度所有的数字,这可能吗?最佳答案必须明白..

+1

@vijayP它的数字是'.'作为小数点,'''作为千位分隔符。 – Justinas

+0

@LinkinTED你能告诉我你怎么能发现这是重复的,因为我有搜索这么多的方式,我已经添加到我的问题的链接,但我找不到这个? –

+0

@trincot你能告诉我这个吗? –

回答

4

使用正则表达式匹配数量,敷在<span>

$(document).ready(function() { 
 
    $('.main_div p').each(function() { 
 
    $(this).html(
 
     $(this).text().replace(/([0-9]+[.,][0-9]+|[0-9]+)/g, '<span>$1</span>') 
 
    ); 
 
    }) 
 
});
span { 
 
    text-decoration: underline; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="main_div"> 
 
    <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles? I am years old 24, because of 24.</p> 
 
    <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?</p> 
 
</div>

+2

这复制文本。我不明白为什么这会收集选票。 – trincot

+0

@trincot对不起,我的坏。编辑 – Justinas

+1

*“难道这不会取代'我的年龄是24岁吗?我年龄大到 24.我老了吗?“* ;-) – trincot

3

使用正则表达式了div html(或text如果你害怕惹HTML)。

使用接受匹配的函数替换正则表达式匹配。也使得处理潜在的边缘情况变得更容易。

var html = jQuery("div.main_div").html(); 
 
console.log(html); 
 
html = html.replace(/(\d*,\d+|\d*\.\d+|\d+)/ig, function(match) { 
 
    return '<span style="background-color:yellow">' + match + '</span>'; 
 
}); 
 
console.log(html); 
 
jQuery("div.main_div").html(html)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="main_div"> 
 
    <p>A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?</p> 
 
</div>

正则表达式包括3个捕获标记:

\d*,\d+|匹配后跟一个.digit任何量,然后通过至少一个digit

\d*\.\d+匹配任何数量的digit后跟一个,后跟至少一个digit

\d+匹配至少一个digit

+0

难道那也不会取代'我的年龄是24.我老到'我的年龄是 24.我老了吗? – Justinas

+0

这样会改变正则表达式 –

相关问题