使jquery.ajax()http请求像普通的html一样行为



所以,我正在使用jquery.ajax()提出HTTP请求,并在我的页面上显示为纯文本显示XML feed。

不过,在发生这种情况之前,我提示用户在该特定的提要中键入要搜索的单词。

问题是,当我想发现该单词时,当它显示为用户窗口上的文本时,要突出显示,例如,例如具有红色的背景色。我已经尝试了所有事情,但我似乎无法使它起作用,我怀疑,因为我需要先以某种方式解析它。

这是代码:

function search(ans) {
var url = "SOME_XML_FEED"
$.ajax({
    url: url,
    dataType: "html",
    crossDomain: "true",
    success: function (response) {
        var n = response.search(ans); //Where the word is found.
        var ansReplacement = '<p style="color: #ffffff; background-color: #ff0000">' + ans + '</p>';
        ans = response.replace(ans, ansReplacement);
        if (ans === response) {
            alert("The string was not found in a text with " + response.length + " letters.");
        } else {
            alert("The string was found at position: " + n + " in a text with " + response.length + " letters.");
        }
        $('#demo').text(ans);
    }

预先感谢。

使用全局正则拨号来查找字符串的所有出现,然后使用JQUERY的.html()方法分配修改后的HTML,而不是.text()

let toHighlight="in",
	$sampleText = $("#sampleText"),
	originalText = $sampleText.text(),
	highlightedText = originalText.replace(new RegExp(toHighlight, "gi"), `<span class="highlight">${toHighlight}</span>`)
$sampleText.html(highlightedText)
.highlight {
  color: #ffffff;
  background-color: #ff0000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sampleText">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tempus, sem at vehicula bibendum, magna arcu accumsan massa, eget porta velit odio ac lectus. Nullam erat sapien, consectetur in tortor eget, rhoncus commodo neque. Maecenas accumsan molestie arcu ac scelerisque. Etiam molestie velit in dolor rutrum, at vehicula mauris volutpat. Ut lobortis dui in maximus elementum. Maecenas quis orci non ligula lobortis aliquam.</div>

您使用的是"文本"功能将HTML粘贴到" #demo"div中。这剥离了HTML。尝试使用" HTML"功能:

        $('#demo').html(ans);

最新更新