如何替换.data javascript函数中的逗号(使用.replace)
How to replace comma inside .data javascript function (with .replace)
在对div列表进行排序时,我正在尝试从提取的值中替换逗号(使用.data)。
带逗号的值无法正确排序。如何使用替换函数对div 进行正确排序?
<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>
我试过这个:
<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>
你应该使用toString()
然后replace()
像下面这样函数。顺便说一句,html第一行可能是您使用div
而不是button
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<div class="table">
<div class="cell" data-number="1,942">1,942</div>
<div class="cell" data-number="42">42</div>
<div class="cell" data-number="161">161</div>
<div class="cell" data-number="5,382">5,382</div>
<div class="cell" data-number="892">892</div>
<div class="cell" data-number="4">4</div>
<div class="cell" data-number="38">38</div>
</div>
<script>
$("button").click(function () {
var divList = $(".cell");
divList.sort(function (b, a) {
return $(a).data("number").toString().replace(/,/g, '') - $(b).data("number").toString().replace(/,/g, '');
});
$(".table").html(divList);
});
</script>
尝试以下操作:
$(".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(',', ''));
});
});
这是演示
相关文章:
- 在正则表达式中,如果第一个圆括号没有't匹配,当在JavaScript中使用replace()与在Ruby中使用
- 使用replace方法替换innerHTML以及在Javascript中不起作用的正则表达式
- 我想使用replace函数扫描json对象,然后用字符串替换匹配的单词
- 考虑到我在JavaScript中使用.replace.更改了特定单词中间的另一个字符,我如何在该单词之前添加字符
- 如何在jquery中使用replace和regex在单词的大写字符前插入空格
- 使用 replace() 丢弃字符串中的动态字符
- 使用 .replace() 将句点更改为下划线
- 如何替换.data javascript函数中的逗号(使用.replace)
- 有选择地使用 replace()
- 如何在 Javascript 中使用 .replace
- 在iframe中使用replace方法的Javascript
- 使用Replace With返回数组的最后一个值
- 对ng重复的结果使用replace将下划线替换为空格
- 除了问号'之外,所有东西都在替换',使用replace()
- 如何在javascript中对正则表达式数组使用replace
- 使用replace修改src属性
- 在对象键中使用正则表达式子模式(使用.replace())
- 如何使用.replace和match()方法
- 对正则表达式使用replace()
- 使用.replace将文本替换为HTML