如何在.data javascript函数中替换逗号(使用.replace)
在对div列表进行排序时,我试图从提取的值中替换逗号(使用.data) 带逗号的值排序不正确。如何使用replace函数对div进行正确排序如何在.data javascript函数中替换逗号(使用.replace),javascript,jquery,sorting,replace,str-replace,Javascript,Jquery,Sorting,Replace,Str Replace,在对div列表进行排序时,我试图从提取的值中替换逗号(使用.data) 带逗号的值排序不正确。如何使用replace函数对div进行正确排序 <script> $(".button").click(function(){ var divList = $(".cell"); divList.sort(function(b, a){ return $(a).data("number")-$(b).data("numbe
<script>
$(".button").click(function(){
var divList = $(".cell");
divList.sort(function(b, a){
return $(a).data("number")-$(b).data("number")
});
$(".table").html(divList);
});
</script>
<div class="button">Click</div>
<div class="table">
<div class="cell" data-number="1,942"></div>
<div class="cell" data-number="42"></div>
<div class="cell" data-number="161"></div>
<div class="cell" data-number="5,382"></div>
<div class="cell" data-number="892"></div>
<div class="cell" data-number="4"></div>
<div class="cell" data-number="38"></div>
</div>
$(“.button”)。单击(函数(){
var divList=$(“.cell”);
divList.sort(函数(b,a){
返回$(a).数据(“数字”)-$(b).数据(“数字”)
});
$(“.table”).html(divList);
});
点击
我试过这个:
<script>
$("button").click(function(){
var divList = $(".cell");
divList.sort(function(b, a){
return $(a).data("number").replace(/,/g, '')-$(b).data("number").replace(/,/g, '')
});
$(".table").html(divList);
});
</script>
$(“按钮”)。单击(函数(){
var divList=$(“.cell”);
divList.sort(函数(b,a){
返回$(a).data(“number”).replace(/,/g')-$(b).data(“number”).replace(/,/g'))
});
$(“.table”).html(divList);
});
尝试以下操作:
$(".button").click(function() { // You missed the . for class here
$(".cell").each(function() { // Loop through each cell
// Set the data-number attribute
$(this).attr('data-number', $(this).attr('data-number').replace(',', ''));
});
});
以下是尝试以下方法:
$(".button").click(function() { // You missed the . for class here
$(".cell").each(function() { // Loop through each cell
// Set the data-number attribute
$(this).attr('data-number', $(this).attr('data-number').replace(',', ''));
});
});
以下是您应该使用的
toString()
,然后使用replace()
函数,如下所示。顺便说一句,html的第一行可能是您在使用div
而不是按钮
点击
1,942
42
161
5,382
892
4.
38
$(“按钮”)。单击(函数(){
var divList=$(“.cell”);
divList.sort(函数(b,a){
返回$(a).data(“number”).toString().replace(/,/g')-$(b).data(“number”).toString().replace(/,/g');
});
$(“.table”).html(divList);
});
您应该使用toString()
然后使用replace()
函数,如下所示。顺便说一句,html的第一行可能是您在使用div
而不是按钮
点击
1,942
42
161
5,382
892
4.
38
$(“按钮”)。单击(函数(){
var divList=$(“.cell”);
divList.sort(函数(b,a){
返回$(a).data(“number”).toString().replace(/,/g')-$(b).data(“number”).toString().replace(/,/g');
});
$(“.table”).html(divList);
});
也许您需要使用parseInt
。i、 例如,parseInt($(a).data(“number”).replace(/,/g'))-parseInt($(b).data(“number”).replace(/,/g'))
?也许您需要使用parseInt
。i、 例如:parseInt($(a).data(“number”).replace(/,/g.))-parseInt($(b).data(“number”).replace(/,/g.))
?