简体   繁体   English

为什么我的jQuery模板方法不再适用于jQuery 1.9.1?

[英]Why does my jQuery templating approach not work in jQuery 1.9.1 anymore?

Please see this fiddle: http://jsfiddle.net/VdZJx/2/ 请看这个小提琴: http//jsfiddle.net/VdZJx/2/

$(function()
{
    var li = $($("#link-item-template").html()).find("a").attr({
        href: "javascript:;"
    }).html("Toggle");

    $("ul").append(li);
});

This is a templating approach I, and as I've seen even some other libs are using to store and generate html templates. 这是一个模板化的方法我,正如我所见,甚至一些其他的lib用于存储和生成html模板。

If you take the jQuery version 1.9.1, let this demo run and watch the console it turns out that Sizzle throws the following error when you try to generate a new jQuery object out of $().html() . 如果您使用jQuery版本1.9.1,让这个演示运行并观察控制台,当您尝试从$().html()生成新的jQuery对象时, Sizzle会抛出以下错误。 See: 看到:

Uncaught Error: Syntax error, unrecognized expression: <li> <input type="checkbox" /> <a></a> </li> 未捕获错误:语法错误,无法识别的表达式:<li> <input type =“checkbox”/> <a> </a> </ li>

What can I do to get it to work again? 我该怎么办才能让它再次发挥作用?

As you are not really getting proper elements, but the contents of a script tag as a string, which happens to be HTML, a lot of whitespace and newlines is added to the HTML string, and you need to trim that to make it work as a valid selector : 由于您没有真正获得正确的元素,但脚本标记的内容为字符串(恰好是HTML),HTML字符串中添加了大量的空格和换行符,您需要对其进行修剪以使其工作为有效的选择器:

$($.trim($("#link-item-template").html()))

FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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