Javascript 如何使用jQuery获取元素中的第一个数字
我有一个HTML代码,如下代码所示,我想用jQuery中的Javascript 如何使用jQuery获取元素中的第一个数字,javascript,jquery,html,string,text,Javascript,Jquery,Html,String,Text,我有一个HTML代码,如下代码所示,我想用jQuery中的.each()循环从中获取第一个数字,并删除重复的数字。怎么样 $('.sada')。每个(函数(){ num=$(this.text(); $('.d')。追加(''+num+''); }); 类似问题:09214239397 使用:09126723272 093342397重定向 使用,jQuery:09354239397 884512545 对象,带有:09126723272 093342397 您可以循环divs并将数字与re
.each()
循环从中获取第一个数字,并删除重复的数字。怎么样
$('.sada')。每个(函数(){
num=$(this.text();
$('.d')。追加(''+num+'');
});代码>
类似问题:09214239397
使用:09126723272 093342397重定向
使用,jQuery:09354239397 884512545
对象,带有:09126723272 093342397
您可以循环divs
并将数字与regex
匹配
var numbers = [];
$(".m .sada").each(function() {
// match and get the first number
var number = $(this).html().match(/(\d+)/)[0];
// check with inArray to get unique
if( numbers.indexOf(number) == -1 )
numbers.push(number);
});
// numbers now contains all the first numbers as array
console.log(numbers);
由于我不确定您是否只想替换div中的内容,下面是第二个示例,用于替换.sada
div中的内容并过滤唯一的数字
我将使用数组来检查是否存在
var numbers = [];
$(".m .sada").each(function() {
var element = $(this),
number = element.html().match(/(\d+)/)[0];
// if first occurence, keep div
if( numbers.indexOf(number) == -1 ) {
element.html(number);
numbers.push(number);
}
// otherwise remove div
else {
element.remove();
}
});
您可以使用中的正则表达式在文本中查找目标编号。还用于检查元素是否包含目标编号
$(.m>.sada”).each(函数(){
var num=$(this.text().match(/([\d]+)/g)[0];
如果(!$(“.d>.sada”).is(“:contains(“+num+”)))
$(“.d”).append(“”+num+“”);
});代码>
类似问题:09214239397
使用:09126723272 093342397重定向
使用,jQuery:09354239397 884512545
对象,带有:09126723272 093342397
这是您想要的
<div class="d"></div>
<div class="m">
<div class="sada">
Similar, Questions : 09214239397
</div>
<div class="sada">
redirect using : 09126723272 09334239397
</div>
<div class="sada">
using,jQuery : 09354239397 884512545
</div>
<div class="sada">
object,with : 09126723272 09334239397
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
var numbers = [];
$('.sada').each(function (array, callback) {
items = $(this).text().split(" ");
$.each(items, function (index, item) {
item = $.trim(item);
if ($.isNumeric(item)) {
if (numbers.indexOf(item) < 0) {
numbers.push(item);
}
}
});
});
$.each(numbers, function (index, item) {
$('.d').append('<div clas="sada">' + item + '</div>');
});
</script>
类似问题:09214239397
使用:09126723272 093342397重定向
使用,jQuery:09354239397 884512545
对象,带有:09126723272 093342397
var数=[];
$('.sada')。每个(函数(数组、回调){
items=$(this.text().split(“”);
$。每个(项目、功能(索引、项目){
项目=$.trim(项目);
如果($.isNumeric(项目)){
if(编号索引(项目)<0){
数字。推送(项目);
}
}
});
});
$。每个(数字、功能(索引、项目){
$('.d')。追加(''+项+'');
});
类为s9的div包含什么?@Mohammad是的,我想获取第一个数字,删除其他文本并删除重复的数字。您应该使用text()
而不是html()
@j08691,看看我的示例,告诉我在哪里可以看到双数字?每个数字相差一位。您的解决方案只返回每个.sodo
div的第一个数字。啊,您是对的。你的例子不同于我用作参考的OP的代码。如何删除重复的数字。