jQuery + client-side template = “Syntax error, unrecognized expression”

后端 未结 6 1033
离开以前
离开以前 2020-12-04 19:09

I just updated jQuery from 1.8.3 to 1.9, and it started crashing all of a sudden.

This is my template:



        
相关标签:
6条回答
  • 2020-12-04 19:23

    As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

    If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

    0 讨论(0)
  • 2020-12-04 19:26

    I had the same error:
    "Syntax error, unrecognized expression: // "
    It is known bug at JQuery, so i needed to think on workaround solution,
    What I did is:
    I changed "script" tag to "div"
    and added at angular this code
    and the error is gone...

    app.run(['$templateCache', function($templateCache) {
        var url = "survey-input.html";
        content = angular.element(document.getElementById(url)).html()
        $templateCache.put(url, content);
    }]);
    
    0 讨论(0)
  • 2020-12-04 19:30

    Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9

    http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring

    0 讨论(0)
  • 2020-12-04 19:33

    I guess your template is starting with a space or a tab.

    You can use jQuery like that:

    $($.parseHtml(modal_template_html)[1]);
    

    or parse the string to remove spaces of the beginning:

    $(modal_template_html.replace(/^[ \t]+/gm, ''));
    
    0 讨论(0)
  • 2020-12-04 19:34

    EugeneXa mentioned it in a comment, but it deserves to be an answer:

    var template = $("#modal_template").html().trim();
    

    This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

    var markup = Mustache.render(template, data);
    $(markup).appendTo(container);
    
    0 讨论(0)
  • 2020-12-04 19:49

    You can use

    var modal_template_html = $.trim($('#modal_template').html());
    var template = $(modal_template_html);
    
    0 讨论(0)
提交回复
热议问题