更改元素内的文本行而不更改其他嵌套元素

时间:2016-05-14 19:17:21

标签: javascript jquery

我想更改div中的文本(因为它是服务器限制的),所以我需要通过脚本更改它。为什么我的javascript无效?

JS:

/Users/james/ClionProjects/United States Computing Olympiad/graphs.cpp:14:5: note: candidate constructor not viable: requires single argument 'l', but no arguments were provided
    Vertex(const int l) : label(l) { }
    ^
/Users/james/ClionProjects/United States Computing Olympiad/graphs.cpp:16:5: note: candidate constructor not viable: requires single argument 'other_vertex', but no arguments were provided
    Vertex(const Vertex& other_vertex) : label(other_vertex.label), adjacent_vertices(other_vertex.adjacent_vertices){ }
    ^
/Users/james/ClionProjects/United States Computing Olympiad/graphs.cpp:15:5: note: candidate constructor not viable: requires 2 arguments, but 0 were provided
    Vertex(const int l, vector<Vertex> adjacents) : label(l), adjacent_vertices(adjacents) { }

HTML屏幕截图:

enter image description here

修改:当我将$(function() { $(".byline:contains('May)").html('Posted during period of May'); }); 修改为('May)(May)时,新问题是('May')也被替换,我只想要替换包含"geplaatst door"

的行

3 个答案:

答案 0 :(得分:1)

:contains('May) =&gt;中有额外的单引号:contains(May)

编辑:要仅更改.byline的1个特定子项,您只需要选择一个特定的子元素,而不是整个父元素

<强> EDIT2

  • 如果您只想将确切文本May替换为新文本,则可以使用正则表达式替换,其中/.../g表示全局替换,如果文本{{1可以多次出现:

    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元素的整个文本部分,那么它会变得更复杂 - 要么避免通过编辑HTML将文本包装到自己的元素(如May),或查看Is there an alternative to jQuery / sizzle that supports textNodes as first class citizens in selectors?,或者使用更复杂的正则表达式:

    <span class="date">May, 2015</span>

小提琴:https://jsfiddle.net/Aprillion/f6mcawd1/3/

正则表达式解释:https://regex101.com/r/hL1eN7/

$(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);
});

答案 1 :(得分:0)

看起来你错过了5月份的单曲报价。

$(".byline:contains('May')").html('Posted during period of May');

这里的工作示例:https://jsfiddle.net/b55Lv052/

答案 2 :(得分:0)

您可以尝试这种方法:您必须扩展选择器,它才能正常工作

$(“。byline&gt; span:contains('May)”)。html('在五月期间发布');`