首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery锚标签文本重写项目

jQuery锚标签文本重写项目
EN

Stack Overflow用户
提问于 2012-03-07 04:17:34
回答 5查看 418关注 0票数 1

我有一个wordpress网站,它列出了一个目录中的文件。代码会被输出为

代码语言:javascript
复制
<a href="http://helpdesk-3/acme/wp-content/uploads/important_documents/compliance_documents/sample_document.pdf">sample_document.pdf</a>

我正在尝试使用jQuery将链接显示文本重写为驼峰式大小写,没有扩展名和空格。因此,它将运行并重写为

代码语言:javascript
复制
<a href="http://helpdesk-3/acme/wp-content/uploads/important_documents/compliance_documents/sample_document.pdf">Sample Document</a>

有没有人有建议?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-03-07 04:27:33

代码语言:javascript
复制
$('a').each(function() { // Loop over all links
    var txt = $(this).text().split('.'); // Link contents, split on '.'
    txt.pop(); // remove last (the extension)
    txt = txt.join('.').replace(/_/g, ' '); // replace '_' with spaces
    txt = $.map(txt.split(' '), function(v) { // split on spaces
        // and uppercase the 1st letter
        return v.substring(0, 1).toUpperCase() + v.substring(1, v.length);
    }).join(' ');
    $(this).text(txt); // set the new text
});​

演示:http://jsfiddle.net/f6x9P/1/

票数 3
EN

Stack Overflow用户

发布于 2012-03-07 04:29:14

既然您使用的是Wordpress,那么只使用PHP可能会更容易一些。

代码语言:javascript
复制
<?php
    $doc = 'sample_document.pdf';
    $array = explode('.', $doc);
    $string = ucwords(str_replace('_', ' ', $array[0]));
    echo $string;
票数 1
EN

Stack Overflow用户

发布于 2012-03-07 04:28:33

代码语言:javascript
复制
//setup function to capitalize each word in a string, breaking the string at the underscore characters
function capitalize (str) {

        //get each word
        var split = str.split('_');

        //loop through the words
        for (var i = 0, len = split.length; i < len; i++) {

            //set the first letter to uppercase, and the rest to lowercase
            split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
        }

        //now return the new string, words separated by spaces
        return split.join(' ');
}

//select the elements you want to update, then update their text
$('a').text(function (index, oldText) {
    return capitalize(oldText);
});

这将照顾到空间。

当您向.text()传递一个函数时,您要求循环遍历选定的元素,并更新它们的文本。无论您选择的内容是什么,都将是新文本,匿名函数将传递选定内容中当前元素的索引和当前元素的值:http://api.jquery.com/text

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9591186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档