我有一个网站(在WordPress中),它使用jQuery来显示内容(本身在functions.php中“计算”)。基本上,需要根据用户标准显示的内容是用PHP加载的,并用jQuery显示。
问题是文本是以大写字母显示的,这与设计的psd不匹配。我尝试了在StackOverflow上找到的许多函数,但它们总是在用户键入数据时使文本大写,而我需要将以大写形式加载的文本大写,并且需要转换为大写文本。
下面是我尝试过的代码:
$.fn.capitalize = function () {
$.each(this, function () {
var caps = this.value;
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
this.value = caps;
});
return this;
};
$.each( tbllPosts, function( key, value ) {
$('.results').prepend('<div class="col-6"><col="row">'+
'<a href="'+wp.url+'" class="text-center"><h3 class="title">'+value.titre+'</h3></a>'+
'</div>'+
'</div>');
$('.title').capitalize();
});显示内容,不起作用的是大写。感谢您的帮助,谢谢!
刚刚检查过了,我有这个错误:
Uncaught TypeError: Cannot read property 'charAt' of undefined发布于 2018-10-26 17:20:21
.val()方法主要用于获取表单元素的值,如输入、选择和文本区域
在这种情况下,您应该使用text()。
此外,您不会向函数发送任何参数。这就是它返回undefined的原因。
我简化了你的代码(因为你没有共享任何html ),所以我可以做一个工作示例。
我还使用trim()删除了文本开头的空格,这样charAt(0)将返回第一个字母,而不是空格。
请在下面检查
$.fn.capitalize = function(t) {
$.each(t, function() {
let caps = t.text().trim();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
t.text(caps)
});
return this;
};
const title = $('.title')
$.fn.capitalize(title);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title">
capitalize me
</p>
另外,你说的Well, the CSS property text-transform: capitalize; doesn't work,是什么意思?它不会被申请?你检查过开发检查器了吗?
发布于 2018-10-26 17:56:35
我会以不同的方式处理它,而不是试图在插入文本后更新它-我会将titre作为一个直接的javascript函数传递给大写函数。
这很困难,因为我不知道您正在使用的数据结构,但我已经做了一些工作,以便将值传递给函数,因为它是预先添加到results div的。我还提供了几个大小写不同的字符串,以显示返回值的大小写正确。
var tbllPosts = [
{url: "url1", titre: "sample string 1"},
{url: "url2", titre: "sample String 2"},
{url: "url3", titre: "SAMPLE STRING 3"}
];
tbllPosts.forEach(function(post){
$('.results').prepend('<div class="col-6"><col="row"><a href="'+post.url+'" class="text-center"><h3 class="title">'+ capitalize(post.titre)+'</h3></a></div></div>');
});
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results"></div>
请注意,如果您想要大写字符串中每个单词的第一个字母,只需在空格“”处拆分字符串,并通过函数传递每个单词。
var tbllPosts2 = [
{url: "url1", titre: "sample string 1"},
{url: "url2", titre: "sample String 2"},
{url: "url3", titre: "SAMPLE STRING 3"}
];
tbllPosts2.forEach(function(post){
$('.results2').prepend('<div class="col-6"><col="row"><a href="'+post.url+'" class="text-center"><h3 class="title">'+ titleCase(post.titre)+'</h3></a></div></div>');
});
function titleCase(str) {
var strArr = str. split(' ');
var newStrArr=[];
strArr.forEach(function(word){
newStrArr.push(capitalize(word))
})
return newStrArr.join(' ');
}
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results2"></div>
https://stackoverflow.com/questions/53005225
复制相似问题