简体   繁体   中英

How do I keep the html raw for anchor tags when using jQuerys .html function?

I have a file that I'm parsing to JSON. I then take that file convert it to html and then display it in a modal. Everything is fine except it takes my anchor tags and displays them as the text encapsulated in the anchor and then makes the link live. I just want it to keep the raw html. Ex. <a id="foo" href="google.com">bar<a/> and not just a live link inside the JSON file that says "bar". I tried to using .text() as opposed to .html() but then its unreadable.

 $.ajax({
    type: "POST",
    data: $.toJSON(param),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "SomePage.aspx/someMethod",
    success: function (data) {
        var myObj = JSON.parse(data.d);

            //put the json file in modal window
            $('#jsonViewTitle').text("H2 Title inside of modal);
            $('#jsonViewBody').html(myObj._jsonfile);
        }
    },
});

EXAMPLE when using .html() - Please note the JSON file is much much longer then this but this should give you an idea. You can click on "bar" and it would take you to google.com

      "META": {
        "NAME": "Donald Trump",
        "CREATED": "2017-06-12",
        "UPDATED": "2017-06-12",
        "LANGUAGE": "en",
        "This name changes" "bar"
    },

EXAMPLE using .text()

    "META": {"NAME": "Donald Trump","CREATED": "2017-06-12","UPDATED": "2017-06-12","LANGUAGE": "en","This name changes" : "<a id="foo" href="google.com">bar</a>"},

This code will search the entire JSON file for the angle bracket ie < and then replace it with &lt which is the less than sign. I added //g which performs a global match by way of regex in the event that there are multiple anchor tags

$('#jsonViewBody').html('<pre><code> ' + myObj._jsonfile.replace(/</g, '&lt;') + '</code></pre>'); 

a script tag may help

<script style="display: block">
    <a id="foo" href="google.com">bar<a/>
</script>

Add specific tags inside your modal to accept the code you want inserted...

 var text = "This is a test sentence"; var foo = "<a href='#'>Test link</a>"; var lorem = "lorem ipsum"; $('#modal #first').text(text); $('#modal #second').text(foo); //$('#modal #second').html(foo); $('#modal #third').text(lorem);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="modal"> <span id="first"></span> <span id="second"> </span> <span id="third"> </span> </div>

You can uncomment the third line of the JS to html() The choice is yours.

Remember that if you use .text() or .html() they will overwrite anything inside the targetted div eg your modal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM