替换整个文档JQuery中的字符

replacing characters in entire document JQuery

本文关键字:字符 JQuery 文档 替换      更新时间:2024-01-27

我尝试了很多不同的方法,但都不起作用。现在我有:

    $(document).ready(function () {
    $(".page").click(function () {
        var html = $(document).html();
        html.replace("[", "<");
        alert("here");
    });

 });

这是行不通的。它也不允许我做任何事情Jquery exmaples如何进行,例如

  $("[").replaceWith("<");

在我看来.replace甚至不在jQuery中,尽管许多示例似乎都将其作为查询的一部分。有什么建议吗?这开始让我很沮丧。我试着传入一个特定的div,但它仍然不起作用。有什么想法吗?如有任何帮助,我们将不胜感激!

这就是您想要的吗?

$(document.documentElement).html(function(i,val){
    return val.replace(/'[/g,'<');
});

文档本身不是DOM Element,您应该使用document.docentElement

线路html.replace("[", "<");没有做任何

html是一个字符串,因此您将替换该字符串,而不对输出执行任何操作。

var foo = html.replace(/'[/g, "<");
$(document).html(foo);

在我看来,您正在从html创建一个变量,但没有将其发送回页面:

$(document).ready(function () {
    //EDIT:
    // $(".page").click(function () { changed to a bind type event handler to
    // prevent loss of interactivity. .on() requires jQuery 1.7+ I believe.
    $(".page").on('click', function () {   
           var htmlString = $('body').html();
            // To replace ALL occurrences you probably want to use a regular expression
            // htmlString.replace(/'[/g, "<");
            htmlString.replace("[", "<");

            //Validate the string is being manipulated
            alert(htmlString);
            // Overwrite the original html
            $('body').html(htmlString);
    });
});

请记住,我还没有测试过这一点,但如果我没有弄错的话,jQuery中的.html()方法用于获取/设置,而不一定用于直接操作。