Why can't I add a
with JQuery .html?

前端 未结 4 841
一个人的身影
一个人的身影 2021-01-04 07:32

Why does this code work:

$(\'div.error_container\').html(\'
No more foo allowed
\');

But this code cau

相关标签:
4条回答
  • 2021-01-04 07:36

    Try breaking it up into a chain:

    var $div = $('<div class="error"></div>').html('No more foo allowed')
                                             .append('<br />');
    $('div.error_container').html($div);
    
    0 讨论(0)
  • 2021-01-04 07:39

    This works perfectly for me:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
      $('div.error_container').html('<div class="error">No more foo allowed<br /></div>');
    });
    </script>
    </head>
    <body>
    <div class="error_container">
    </div>
    </body>
    </html>
    

    in Chrome and Firefox. What version of jQuery are you using?

    On a side note <br /> is XML (including XHTML) not HTML. HTML is <br>.

    0 讨论(0)
  • 2021-01-04 07:42

    I also had a similar issue, not sure if it is relevant. I was doing c# mvc for a cms.

    So i had some html input from user and i display them using "@Html.Raw(Modal.Content)"

    Inside the Modal.Content there was a <br /> and i had issue appending that content into the html using jquery .html("@Html.Raw(Modal.Content)")

    But in the end the issue was not <br />

    There is an invisible \n so i did .html("@Html.Raw(Modal.Content).Replace("\n", "")") and the issue was solved. The <br> remained in my content and it work as expected.

    0 讨论(0)
  • 2021-01-04 07:55

    I tried the following SSCCE and it works flawlessly in IE, FF, Safari, Opera and Chrome (all of the most recent versions).

    So your problem is likely related with the doctype you declared or using an old version of Chrome.

    <!doctype html>
    <html lang="en">
        <head>
            <title>SO question 2173556</title>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
            <script>
                $(document).ready(function() {
                    $('#foo').html('<div>foo<br>foo</div>');
                    $('#bar').html('<div>bar<br/>bar</div>'); // Yes, that's illegal in HTML strict. Just to test :)
                });
            </script>
            <style>
    
            </style>
        </head>
        <body>
            <div id="foo"></div>
            <div id="bar"></div>
        </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题