开发者

jQuery render HTML as plain text w/ toggle (toggle is working fine, but cannot covert the HTML to text)

Below is my current code. And it is working fine, but I need the .code class element to display as plain text and not render as HTML.

jQuery:

$(document).ready(function( ) {
 $('.code').hide();
 $('.codeLink').toggle(
    function() {    
   $(this).next('.code').fadeIn();
     $(this).addClass('close');
    },
    function() {
      $(this).next('.code').fadeOut();
        $(this).removeClass('close');
  }
); // end toggle
});

HTML:

<a开发者_JAVA技巧 class="codeLink" style="margin-bottom: 10px; display: block;" href="#">Get The   Code</a>
<div class="code"><a class="benefitsQandA" href="#">Get an Instant Quote &amp;    Apply</a></div>

This section of the .code class should display on the screen exactly like this (in other words not rendered as HTML just as text):

<a class="benefitsQandA" href="#">Get an Instant Quote &amp; Apply</a>


try this:

$(".code").text($(".code").html());

of course, if you are doing that to multiple divs, you would need to use .each:

$(".code").each(function(){
    $(this).text($(this).html());
});


Use $(".code").text($(".code").html())


The proper way to handle this is to escape the code you don't want the browser to render, like this:

<a class="codeLink" style="margin-bottom: 10px; display: block;" href="#">Get The Code</a>
<div class="code">&lt;a class="benefitsQandA" href="#"&gt;Get an Instant Quote &amp;amp; Apply&lt;/a&gt;</div>

If you don't then you aren't guaranteed the correct output from the browser since JQuery's .html() tag is a wrapper for .innerHTML (See http://api.jquery.com/html/) which doesn't always return the exact same markup that you use.

You can take a look at a tool like the one at http://accessify.com/tools-and-wizards/developer-tools/quick-escape/ to do the escaping for you.

Wikipedia also has a reference of XML/HTML entity codes


Could you not do this from the server?

When the user hits the toggle button pass the html to the server, using php replace the < and > characters with &lt; and &gt; and return the html back to the page.

unless you are dealing with a very large amount of data this shouldn't take long to process. and this way you will get 100% exactly what the original markup is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜