JavaScript 一次替换文本中的多个字符

我有一个表格,我试图根据表格中的值对其进行着色。因此,如果表中的值为 150%,则单元格将变为红色。如果表中的值为 50%,则该值将显示为绿色。但是,由于某种原因,表中的实际文本内部有大量空格以及 % 符号。如何用空字符 ('') 替换任何空格和 '%' 字符?


这是我所拥有的不起作用的:


<script type="text/javascript">


        $(document).ready(function () {

            $('#myTable td.PercentMem').each(function () {

                if ($(this).text().replace(/\s/g, '').replace('%', '') >= '100') {

                    $(this).css('background-color', '#ff0000');

                }

                else {

                    $(this).css('background-color', '#33cc33');

                }

            });

        });


    </script>

谢谢你!


编辑


我很笨。我忘记了这些百分比有小数点这一事实。所以,我真正处理的是类似“50.89%”的东西,到目前为止提供的解决方案将其转换为“5089”。如何保留小数?


翻翻过去那场雪
浏览 53回答 2
2回答

慕桂英546537

您需要删除所有非数字字符并将结果字符串转换为 int。所以像这样parseInt($(this).text().replace(/\D/g,'')):另外,在您的帖子中,您正在与 string 进行比较'100',这显然应该是一个数字。尝试这个:&nbsp; &nbsp; &nbsp; &nbsp; $(document).ready(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#myTable td.PercentMem').each(function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (parseInt($(this).text().replace(/\D/g,'')) >= 100) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).css('background-color', '#ff0000');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).css('background-color', '#33cc33');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });免责声明:我还没有实际测试过这个,但这应该有效。

慕桂英3389331

你可以用这个来实现,避免使用 jQuery 来选择元素,使用纯 JavaScript:const myCells = document.querySelectorAll('.PercentMem');myCells.forEach(cell => {&nbsp; const cellValue = cell.textContent.replace(/\D+/g, '');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; cell.classList.toggle(parseInt(cellValue) >= 100 ? 'red' : 'green');});这是包含所有代码的完整小提琴手。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript