从字符串模板中删除元素

时间:2014-02-22 00:34:19

标签: javascript jquery

我有一个名为_categoryItemDivTemplate的JavaScript字符串,用于定义HTML标记,包括<div> class="MakeTopLevelCategory"

我以为我可以使用以下代码删除<div>

item = $(_categoryItemDivTemplate);
if (!isTopLevel)
    item.remove('div.MakeTopLevelCategory');

但它没有效果。

我错过了什么吗?是否有必要先将项目添加到DOM?

修改

以下是代码中的模板:

var _categoryItemDivTemplate =
    '<div class="CategoryItem" style="clear:both;">'
    + '<div class="CategoryHeader">'
    + '<img src="/images/plus.gif" class="Icon"/>'
    + '<img src="/images/icn_folder.gif" class="Icon"/>'
    + '<span class="Title">&nbsp;</span>'
    + '<div style="float:right; font-size: 11px;" class="CategorySelector">'
        + '<div class="DeleteCategory" title="Delete this Category">&nbsp;</div>'
        + '<div class="EditCategory" title="Rename this Category">&nbsp;</div>'
        + '<div class="MakeTopLevelCategory" title="Make this Category a Top-level Category">&nbsp</div>'
        + '<div class="MoveSubcategory" title="Move this Category">&nbsp;</div>'
        + '<div class="SubcategoryMarker AddSubcategory" title="Add a new Subcategory to this Category">&nbsp;</div>'
        + '<div class="PackageCostingMarker AddPackage" title="Add a new Package to this Category">&nbsp;</div>'
        + '<div class="ProductCostingMarker AddProduct" title="Add a new Product to this Category">&nbsp;</div>'
        + '<div class="NarrativeMarker AddArticle" title="Add a new Article to this Category">&nbsp;</div>'
    + '</div>'
    + '</div>'
    + '<div class="CategoryItems" style="display: none;">'
    + '</div>'
    + '</div>';

1 个答案:

答案 0 :(得分:1)

从对象中删除它不会将其从字符串中删除,如果你想从字符串中删除它,那么你需要用对象源替换字符串,所以试试

item = $('<div />', {html:'_categoryItemDivTemplate'});
if (!isTopLevel) {
    item.find('div.MakeTopLevelCategory').remove();
}