替换整个文档JQuery中的字符

时间:2012-07-23 20:29:58

标签: javascript jquery

我已经尝试了许多不同的方法,但没有任何工作。现在我有:

    $(document).ready(function () {
    $(".page").click(function () {

        var html = $(document).html();

        html.replace("[", "<");

        alert("here");
    });


 });

这拒绝工作。它也不允许我做任何Jquery exmaples例如

的事情
  $("[").replaceWith("<");

在我看来,.replace甚至不在jQuery中,尽管很多例子似乎都将它作为查询的一部分。有什么建议?这开始让我感到沮丧。我试过传递一个特定的div,它仍然拒绝工作。有任何想法吗?任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:5)

这是你想要的吗?

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

document本身不是DOM Element,您应该使用document.documentElement代替。

答案 1 :(得分:0)

在我看来,你是从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()方法用于获取/设置不一定要直接操作。

答案 2 :(得分:0)

html.replace("[", "<");行没有做任何事情

html是一个字符串,所以你要替换字符串而不对输出做任何事情。

var foo = html.replace(/\[/g, "<");
$(document).html(foo);
相关问题