按数据属性循环元素并替换值

loop elements by data attribute and replace values

本文关键字:替换 元素 数据属性 循环      更新时间:2023-09-26

我正在尝试循环遍历包含特定数据属性的所有元素,然后替换/删除某些字符。

//replace chars put in by money mask since model is double
$("input[data-input-mask='money']").each(function() {
        alert(this.value); // shows: $ 1,000
        alert('test$ ,'.replace('$ ', '').replace(',', '')); //shows: test
        this.value = this.value.replace('$ ', '').replace(',', '');
        alert(this.value); //shows: $ 1,000
});

this.value仍然是原始值。我在这里可能做错了什么?

使用.localeString()

更新

重读OP之后,我意识到想要的恰恰相反。这仍然很容易。使用localString()而不是使用遮罩。那么,在处理值时就不使用localestring()了。

摘录

$("input[data-input-mask='money']").each(function() {
    var cash = parseFloat(this.value);
    var green = cash.toLocaleString('en-EN', { style: 'currency', currency: 'USD' });
    alert(green);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-mask='money' value="623.23">
<input data-input-mask='money' value="20199">
<input data-input-mask='money' value="">

您可以循环遍历每个元素并像这样替换它。

  <script>
    $(document).ready(function(e) {
            //Retrieve all text of amount di;
            $.each( $('.amount'), function(){
                var unique_id = $(this).text();
   //check if any price is match to FREE THEN replace it with   NOT FREE
                 if(unique_id=='FREE'){
                        $(this).text("NOT FREE");
                 }
            });
    });
    </script>