修复了如何在容器中查找和替换字符串的功能

Fix function on how to find & replace a string within a container

本文关键字:查找 替换 字符串 功能      更新时间:2023-09-26

我在这里做了一个函数:

function locationOfVideo(){//Outputs video location div according to post text
    var ytVideoDiv = '<div class="youtube-video"><div id="<?php echo $divName; ?>-video"></div></div>';
    $j('#main .content:contains("<--video-->")').replace('<--video-->', ytVideoDiv);
}

我以为这会起作用,但我大错特错,有点累。无论如何,我在这里做错了什么?

replace 是一个普通的 js 函数,用于替换字符串或类似字符串的一部分,而不是替换 jQuery 对象的内容。

如果目标是替换所选元素中的所有内容,并且如果您使用的是正确的选择器,则可以使用 html() 并执行以下操作:

$j('#main .content:contains("<--video-->")').html(ytVideoDiv);

或者只替换字符串<--video-->

$j('#main .content:contains("<--video-->")').html(function(i,html) {
    return html.replace('&lt;--video--&gt;', ytVideoDiv)
});​

小提琴

不要在 html 中使用 <--video-->,改成其他类似 {video} 的 。

然后用:

$('#main .content:contains("{video}")').replaceWith(function() {
  return $(this).text().replace('{video}', ytVideoDiv);
});
$j('#main .content:contains("<!--video-->")').replace('<--video-->', ytVideoDiv);

应该是:

var videoNode = $j('#main .content:contains("<!--video-->")');
videoNode.html(videonode.html().replace('<!--video-->', ytVideoDiv));

或:

$j('#main .content:contains("<!--video-->")').html(function(index, oldhtml) { return oldhtml.replace('<--video-->', ytVideoDiv); });

最好输出带有特殊标签的元素,如 abbr,请查看像 jquery-timeago 这样的 JavaScript 模板 usabe:

<abbr class="timeago" title="2011-12-17T09:24:17Z">December 17, 2011</abbr>

取代:

$('abbr.timeago').timeago()