忽略 jQuery 中的某些子元素
我有以下代码:
<table>
<th class="title2">The <i>very</i> hungry school</th><br />
<th class="title2">The very hungry school <span>yeah it works</span></th>
而且......
function capitalise(str) {
if (!str) return;
var counter = 0;
var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
str = str.replace(/\b\S*[a-z]+\S*\b/ig, function(match) {
counter++;
return $.inArray(match, stopWords) == -1 || counter === 1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
});
return str;
}
$('th.title2').each(function() {
var capclone = $(this).clone().children(':not(i)').remove().end();
capclone.text(capitalise(capclone.text()));
capclone.append($(this).children(':not(i)'));
$(this).replaceWith(capclone);
});
这段代码适用于我需要它做的事情,但是有没有办法维护斜体元素。目前它被删除,这不是一个坏的解决方案,但它并不完美。
I have the following code:
<table>
<th class="title2">The <i>very</i> hungry school</th><br />
<th class="title2">The very hungry school <span>yeah it works</span></th>
And..
function capitalise(str) {
if (!str) return;
var counter = 0;
var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
str = str.replace(/\b\S*[a-z]+\S*\b/ig, function(match) {
counter++;
return $.inArray(match, stopWords) == -1 || counter === 1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
});
return str;
}
$('th.title2').each(function() {
var capclone = $(this).clone().children(':not(i)').remove().end();
capclone.text(capitalise(capclone.text()));
capclone.append($(this).children(':not(i)'));
$(this).replaceWith(capclone);
});
This code works for what I need it to do, but is there a way to maintain the italic element. At the moment it gets removed, it's not a bad solution but it's not perfect.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果不使用
text()
使用html()
来获取 html,因为它是元素,然后将每个单词大写。我将正则表达式稍微简化为/\b\w+\b/ig
,它将匹配一个单词边界,后跟一个或多个字符和一个单词边界。这也将匹配 html 标记中的初始字符,但它不会导致任何问题。我没有克隆和替换节点,而是更新了 html,这应该更快,因为它在 DOM 交互上更轻。您可以使用此 fiddle 中的代码。
If instead of using
text()
usehtml()
to get the html as it is the element and then upper case each word. I simplified the regex slightly to/\b\w+\b/ig
which will match a word boundary followed by one or more characters and a word boundary. This will also match the initial character in a html tag, but it shouldn't cause any problems. Instead of cloning and replacing the node I just update the html which should be faster as it's lighter on the DOM interaction.You can play with the code in this fiddle.