javascript jQuery删除类中的最后两个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15671472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:37:41  来源:igfitidea点击:

jQuery Removing last two characters in a class

javascriptjquery

提问by JaggsWaggert

This should be pretty simple. I'm trying to use the slice method to remove the last two characters in a dynamically created string in a shopping cart.

这应该很简单。我正在尝试使用 slice 方法删除购物车中动态创建的字符串中的最后两个字符。

So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.

因此,我希望产品显示为 28 美元,而不是将产品显示为 28.00 美元。由于这些值来自数据库,我不能简单地在变量中定义字符串,就像我在很多教程中看到的那样。

I've created a JSFiddle here: http://jsfiddle.net/EbckS/

我在这里创建了一个 JSFiddle:http: //jsfiddle.net/EbckS/

The jQuery that's not working is below:

不起作用的 jQuery 如下:

    $(".myclass").slice(0,-2);

回答by Ricardo Alvaro Lohmann

You should use text.

你应该使用text.

$(".slice").text(function(i, text) {
    return text.slice(0, -2);
});
  • iReffers the index position of the element in the set
  • textReffers the old text value
  • i引用元素在集合中的索引位置
  • text引用旧文本值

Refference

参考

回答by RN Kushwaha

Very Simple. I uses this for getting number from a string you can use it too.

很简单的。我使用它来从字符串中获取数字,您也可以使用它。

var height= "800px";

var newheight = height.substring(0,height.length-2); //string 800
newheight= parseFloat(newheight) || 0; //number 800