猿问

如何防止 JavaScript 将我的文本添加为​​数字

我有这样的文本: 4.72% - 12.04% 我正在放入一个 JavaScript 对象属性,我试图将其添加到页面中,如下所示:


$("#container").append("<div>" + rates.fixedrates + "</div>");

JavaScript 一直在尝试计算数字,即使这不是我想要做的。它不打印文本,只打印 NaN。


我怎样才能告诉 JS 停止这个?我什至尝试用“-”替换&mdash;它,它做同样的事情。有什么我不知道的可以阻止这种情况吗?


编辑:


数据来自 ajax 调用:


$.ajax({

    url: "/Search/Rates",

    type: "POST",

    dataType: "json",

    data: { oe: ui.item.oe },

    success: function (data) {

        data.forEach(function (rates, index, arr) {

            $("#container").append("<div>" + currentValue.fixedrates + "</div>");

        });

    }

});

控制器:


return Json(rates);

“FixedRates”只是 c# 对象“rates”的一个字符串属性。没什么特别的。


喵喔喔
浏览 151回答 3
3回答

小怪兽爱吃肉

以我只能假设是最标准的方式工作正常 - 您可能在分配值或连接的方式上做错了const rates = {&nbsp; fixedRates: ''};// Joining ourselveslet a = '4.72%';let b = '12.04%';let c = a + ' - ' + b;// Together alreadylet d =&nbsp; '4.72% - 12.04%';rates.fixedRates = c;$("#container").append("<div>" + rates.fixedRates + "</div>");rates.fixedRates = d;$("#container").append("<div>" + rates.fixedRates + "</div>");<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="container"></div>

蝴蝶不菲

好的,为了简洁/清楚起见,我遗漏了附件中的很多内容<div>。我发现我发生了这样的事情:"<div>" + <-- extra plus sign+ rates.FixedRates + "</div>"所以基本上是这样的:"<div>" + + rates.FixedRates + "</div>"我想关于发布所有内容有什么要说的。

慕莱坞森

此解决方案将获取输入并将其转换为文本节点,然后再将其插入到 div 中,然后将其插入到容器中。让我知道这对你有什么影响..$.ajax({&nbsp; &nbsp; url: "/Search/Rates",&nbsp; &nbsp; type: "POST",&nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; data: { oe: ui.item.oe },&nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; data.forEach(function (rates, index, arr) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var div = document.createElement('div');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var textContent = document.createTextNode(currentValue.fixedrates);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var container = document.getElementById('container');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; div.appendChild(textContent);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; container.appendChild('div');&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答