如何让标签内的数字留下文本
这里是我的朋友只感兴趣的电话号码不是文本
<p class="phone-list"> <span>hello</span> <span>8046033006<script type="text/javascript"> whicVer('vers1');</script></span> </p> <p class="phone-list"> <span>hello</span> <span>12345566<script type="text/javascript"> whicVer('vers2');</script></span> </p>
我只想得到电话号码,即。 8046033006
& 12345566
通过这个代码我越来越
$('.phone-list span:nth-child(2)').each(function() console.log($(this).text()); );
输出看起来像东西….
-
8046033006 whicVer('vers1')
-
12345566 whicVer('vers2')
我观察到为什么脚本标记不打印? 请提前帮助我
你可以使用正则expression式。 或者就在这个数字附近使用一点点。
var removedText = initialText.replace(/\D/g, '');
对于你的情况,这将是:
$('.phone-list span:nth-child(2)').each(function() { var num = $(this).text().replace(/\D/g, '') console.log(num); );
这是一个小JSFiddle
假设所有.phone-list
元素的HTML结构都是相同的,那么可以从第二个子span
检索第一个textNode,并获取它的nodeValue
。 尝试这个:
$('.phone-list span:nth-child(2)').each(function() { console.log($(this).contents()[0].nodeValue); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="phone-list"> <span>hello</span> <span>8046033006<script type="text/javascript">//whicVer('vers1');</script></span> </p> <p class="phone-list"> <span>hello</span> <span>12345566<script type="text/javascript">//whicVer('vers2');</script></span> </p>
一旦你从DOM中获取文本,你可以像这样使用正则expression式
// text from which number will be seperated var number = "8046033006hriughidhgiudhgiudthgiuhdiutg" document.write('<pre>'+number.match(/\d+/)[0]+'</pre>')
的jsfiddle