Dynamically changing the HTML of a div with jQuery is causing HTML encoding to be lost

后端 未结 4 1770
栀梦
栀梦 2021-01-28 14:20

I have a piece of code which dynamically alters the HTML of a div called \'accordion\' on the fly like so:

// htmlstring contains some HTML containing some HTML          


        
相关标签:
4条回答
  • 2021-01-28 14:51

    When the HTML code is merged into the DOM, everything is canonicalized into the internal DOM representation, the original HTML coding is irrelevant. Apostrophe and ' are equivalent in HTML code, so they turn into the same thing in the DOM.

    What you need to do is escape the inner apostrophe. htmlstring should contain:

    <span class='clickableComponent component' onclick="ComponentClicked('4612', 'Don\'t know', '44761');">Don't know</span>
    

    Issues like this are one of the reasons why inline Javascript in HTML elements is not recommended. It would be cleaner if you did something like:

    $(".clickableComponent").click(function() {
        ComponentClicked('4612', "Don't know", '44761');
    });
    
    0 讨论(0)
  • 2021-01-28 14:53

    Check this link: HTML-encoding lost when attribute read from input field

    you can use the function that Anentropic write.

    function htmlEscape(str) {
        return String(str)
                .replace(/&/g, '&amp;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
    }
    
    0 讨论(0)
  • 2021-01-28 14:55

    Thanks go to Barmar for providing the first correct answer. In actual fact I refactored my code so that I wasn't passing complicated strings via a method parameter, but my you did answer my initial query correctly.

    Thanks to other comments for your input too.

    0 讨论(0)
  • 2021-01-28 15:10

    Try using the javascript escape \'

    Here's an excerpt from the jQuery docs that explains why your HTML escape character is being rendered:

    By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

    0 讨论(0)
提交回复
热议问题