简体   繁体   English

使用javascript将首字母大写

[英]Capitalize first letter using javascript

I'm trying to capitalize first letter of sentence for every class.我正在尝试将每个班级的句子的第一个字母大写。

I have html <span class="price"></span> multiple time on my page and I want to capitalize first letter of every tag.我的页面上多次使用 html <span class="price"></span>并且我想将每个标签的第一个字母大写。 So I have an array of span classes.所以我有一个跨度类的数组。

Default value of html elements is lowercase, I tried with text-transform:capitalize, it converts first letter of every word. html 元素的默认值是小写,我尝试使用 text-transform:capitalize,它转换每个单词的第一个字母。

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();

        }
    }

Why not stick with jQuery, as you're already using it为什么不坚持使用 jQuery,因为您已经在使用它

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

You can do it with CSS:你可以用 CSS 做到这一点:

.price:first-letter{
   text-transform: capitalize;
}

Your function is basically right.你的功能基本上是对的。 I imagine there is a problem with the jquery?我想jquery有问题吗? I changed it a tiny bit to use javascript.我改变了一点点使用javascript。 https://jsfiddle.net/h6h4nswd/ https://jsfiddle.net/h6h4nswd/

var selectorTest = selector[i].innerHTML;

Iam not sure what you get with your document.getElementsByClassName('price');我不确定你的 document.getElementsByClassName('price'); but this work it will return Toto但这项工作将返回托托

function applySentenceCase() 
{
   var selector = "toto";
   return selector.charAt(0).toUpperCase() + selector.substr(1).toLowerCase();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM