【问题标题】:Capitalize first letter using javascript使用javascript将第一个字母大写
【发布时间】:2016-03-03 20:50:15
【问题描述】:

我正在尝试将每个班级的句子首字母大写。

我的页面上有多次 html <span class="price"></span>,我想将每个标签的首字母大写。所以我有一个跨度类数组。

html元素的默认值是小写的,我试过text-transform:capitalize,它转换每个单词的第一个字母。

我试图写一些代码,但它不起作用,它只循环一次,它不起作用。

这是代码,有人可以帮我修改一下吗

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

        }
    }

【问题讨论】:

  • 您确定要替换字符,但您认为您在哪里返回字符串?

标签: javascript jquery


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我用循环复杂化了一切。这就是我要找的东西!
【解决方案2】:

你可以用 CSS 做到这一点:

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

【讨论】:

    【解决方案3】:

    我不确定你的 document.getElementsByClassName('price'); 会得到什么 但这项工作将返回 Toto

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

    【讨论】:

    • 用 document.getElementsByClassName('price');我正在获取字符串想要更改为大写的所有 html 元素。我的类 div 很少。
    【解决方案4】:

    您的功能基本上是正确的。我想jquery有问题吗?我将其稍作更改以使用 javascript。 https://jsfiddle.net/h6h4nswd/

    var selectorTest = selector[i].innerHTML;
    

    【讨论】:

    • 我知道我遗漏了一些东西,但我不知道是什么。 :) 这绝对是我需要的和平代码。 :) 谢谢。
    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2016-10-20
    相关资源
    最近更新 更多