在创建文档片段时,我遇到了一个问题,(似乎)同时使用jQuery操作片段的类列表并将事件处理程序附加到片段。
我可以查询片段并将元素追加到as you can see in my fiddle.
这是我的代码:
//Test elem
var elem = {
"name" : "Dual Intel Xeon E5 4603 v2 Processor, 2.2GHz 4 core / 8 thread SMT",
"cores" : 4,
"threads" : 8,
"base" : 2.2,
"turbo" : 2.2,
"price" : 1000
}
//Create document fragment using an HTML string
//(backslashes are for escaping carriage returns)
var fragment = createDocFrag
(
"<div class='product'>\
<div class='collapsed'>\
<p class='name'></p>\
<p class='price'><span>£</span></p>\
</div>\
<div class='expanded'>\
<ul>\
<li class='base'><span> GHz Base</span></li>\
<li class='turbo'><span> GHz Turbo</span></li>\
<li class='cores'><span> Cores</span></li>\
<li class='threads'><span> Threads</span></li>\
</ul>\
</div>\
</div>"
);
//These work - the appended elements have these updated properties
$(fragment).find(".name").append(elem.name);
$(fragment).find(".base").prepend(elem.base);
$(fragment).find(".turbo").prepend(elem.turbo);
$(fragment).find(".cores").prepend(elem.cores);
$(fragment).find(".threads").prepend(elem.threads);
$(fragment).find(".price").append(elem.price);
//This doesn't work - the class doesn't appear inside the element in the DOM
if ($(".product.current").length === 0) {
$(fragment).addClass("current");
}
//Neither does this - no class in the DOM, and the click event isn't registered
$(fragment).click(function(){
$(this).toggleClass("expand");
});
//Append fragment to dom
$("body").append(fragment);
//Function for creating document fragment from an HTML String
function createDocFrag(htmlStr) {
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
非常感谢任何帮助。谢谢!
答案 0 :(得分:1)