我有一个wordpress网站,它列出了一个目录中的文件。代码会被输出为
<a href="http://helpdesk-3/acme/wp-content/uploads/important_documents/compliance_documents/sample_document.pdf">sample_document.pdf</a>我正在尝试使用jQuery将链接显示文本重写为驼峰式大小写,没有扩展名和空格。因此,它将运行并重写为
<a href="http://helpdesk-3/acme/wp-content/uploads/important_documents/compliance_documents/sample_document.pdf">Sample Document</a>有没有人有建议?
发布于 2012-03-07 04:27:33
$('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/
发布于 2012-03-07 04:29:14
既然您使用的是Wordpress,那么只使用PHP可能会更容易一些。
<?php
$doc = 'sample_document.pdf';
$array = explode('.', $doc);
$string = ucwords(str_replace('_', ' ', $array[0]));
echo $string;发布于 2012-03-07 04:28:33
//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
https://stackoverflow.com/questions/9591186
复制相似问题