我想更改 div 中的文本(因为它受服务器限制),因此我需要通过脚本更改它。为什么我的 JavaScript 不工作?
JS:
$(function() {
$(".byline:contains('May)").html('Posted during period of May');
});
HTML 屏幕截图:
编辑:当我将 ('May)
修复为 (May)
或 ('May')
时,新问题是"geplaatstdoor"
也被替换了,我只想替换包含May
最佳答案
你在:contains('May)
中有额外的单引号=> :contains(May)
编辑:仅更改 .byline
的 1 个特定子级,您只需选择一个特定的子元素,而不是整个父元素
编辑2:
如果您只想替换确切的文本
May
对于新文本,您可以使用正则表达式替换来执行此操作,其中/.../g
表示全局替换,如果文本May
可以多次出现:$(function() { var elem = $(".byline:contains(May)") var new_html = elem.html().replace( /May/g, "$1Posted during period of May$2"); elem.html(new_html); });
但如果您希望更改
.byline
的整个文本部分包含May
的其他嵌套元素之间的元素,那么它会变得更加复杂 - 要么通过编辑 HTML 将文本包装到其自己的元素(如<span class="date">May, 2015</span>
)来避免这种情况。 ,或参见Is there an alternative to jQuery / sizzle that supports textNodes as first class citizens in selectors? ,或者使用更复杂的正则表达式:$(function() { var elem = $(".byline:contains(May)") var new_html = elem.html().replace( /((?:^|>)\s*)[^<>]+May[^<>]+(\s*(?:<|$))/, "$1Posted during period of May$2"); elem.html(new_html); });
fiddle :https://jsfiddle.net/Aprillion/f6mcawd1/3/
正则表达式解释:https://regex101.com/r/hL1eN7/
/((?:^|>)\s*)[^<>]+May[^<>]+(\s*(?:<|$))/g
1st Capturing group ((?:^|>)\s*)
(?:^|>) Non-capturing group
1st Alternative: ^
^ assert position at start of the string
2nd Alternative: >
> matches the characters > literally
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[^<>]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
<> a single character in the list <> literally (case sensitive)
May matches the characters May literally (case sensitive)
[^<>]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
<> a single character in the list <> literally (case sensitive)
2nd Capturing group (\s*(?:<|$))
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?:<|$) Non-capturing group
1st Alternative: <
< matches the characters < literally
2nd Alternative: $
$ assert position at end of the string
g modifier: global. All matches (don't return on first match)
- 如果您需要更通用的解决方案,而不仅仅是“五月”,请检查 https://stackoverflow.com/a/5090157/1176601
关于javascript - 更改元素内的一行文本而不更改其他嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230863/