使用javascript将首字母大写 [英] Capitalize first letter using javascript

查看:84
本文介绍了使用javascript将首字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为每个班级的首字母大写.

I'm trying to capitalize first letter of sentence for every class.

我的页面上多次显示html <span class="price"></span>,我想将每个标签的首字母大写.所以我有一系列的span类.

I have html <span class="price"></span> multiple time on my page and I want to capitalize first letter of every tag. So I have an array of span classes.

html元素的默认值是小写字母,我尝试使用text-transform:capitalize进行转换,它会转换每个单词的第一个字母.

Default value of html elements is lowercase, I tried with text-transform:capitalize, it converts first letter of every word.

我试图编写一些代码,但是它不起作用,它仅通过一次循环并且不起作用.

I tried to write some code but it doesn't work, it goes through loop only once and it doesn't work.

这是代码,有人可以帮我修改以工作吗

Here is the code, can somebody help me to modify to work

function applySentenceCase() {
    var selector = document.getElementsByClassName('price');
    for( i =0; i<selector.length; i++) {
      var selectorTest = jQuery(selector[i]).text();
      return selectorTest.charAt(0).toUpperCase() + selectorTest.substr(1).toLowerCase();

        }
    }

推荐答案

为什么不坚持使用jQuery,因为您已经在使用它

Why not stick with jQuery, as you're already using it

$('.price').text(function(_, txt) {
    return txt.charAt(0).toUpperCase() + txt.slice(1).toLowerCase();
});

这篇关于使用javascript将首字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆