[英]How to Invoke a Javascript function on the content of a div?
我正在開發一個 WordPress 頁面,需要調用 javascript function (如下所示)將文本轉換為標題大小寫或句子大小寫。 我從以前的帖子中找到了一些我想使用的腳本。 但是,我不知道如何在 DIV 或段落中調用它。
這是我想使用的腳本。 歡迎任何改進此腳本的幫助。
PS:我不想使用 CSS 方法來轉換文本。
String.prototype.toTitleCase = function() {
var i, j, str, lowers, uppers;
str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Certain minor words should be left lowercase unless
// they are the first or last words in the string
lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At',
'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'
];
for (i = 0, j = lowers.length; i < j; i++)
str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'),
function(txt) {
return txt.toLowerCase();
});
// Certain words such as initialisms or acronyms should be left uppercase
uppers = ['Id', 'Tv'];
for (i = 0, j = uppers.length; i < j; i++)
str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'),
uppers[i].toUpperCase());
return str;
}
要運行 function,您需要檢索所有目標元素,在下面的示例中,我使用了div
元素,但 class 或任何其他有效選擇器都可以工作,並且從那里您需要在文本內容上調用toTitleCase()
字符串原型每個元素。 它可能看起來像這樣:
document.querySelectorAll('div').forEach(el => el.textContent = el.textContent.toTitleCase());
這是一個完整的工作示例:
String.prototype.toTitleCase = function() { var i, j, str, lowers, uppers; str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); // Certain minor words should be left lowercase unless // they are the first or last words in the string lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With' ]; for (i = 0, j = lowers.length; i < j; i++) str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) { return txt.toLowerCase(); }); // Certain words such as initialisms or acronyms should be left uppercase uppers = ['Id', 'Tv']; for (i = 0, j = uppers.length; i < j; i++) str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase()); return str; } document.querySelectorAll('.title').forEach(el => el.textContent = el.textContent.toTitleCase());
<h3 class="title">This is an example of title case</h3> <p>This is paragraph text and will not be changed.</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.