如何定位jQuery生成的div标记
我通过jQuery创建了一个新标记,代码如下所示:如何定位jQuery生成的div标记,jquery,html,Jquery,Html,我通过jQuery创建了一个新标记,代码如下所示: new_compare_item = $("<div/>"); new_compare_item.attr("id", "compare_item"); new_compare_item.attr("name", "compare_item"); new_compare_item.addClass("div_image"); new_compare_item.append($("<img/>") .addClass("i
new_compare_item = $("<div/>");
new_compare_item.attr("id", "compare_item");
new_compare_item.attr("name", "compare_item");
new_compare_item.addClass("div_image");
new_compare_item.append($("<img/>")
.addClass("image")
.attr("src", "/compare/sites/default/files/add_item.jpg")
.attr("height", 50)
.attr("width", 50));
new_compare_item.append($("<span/>")
.addClass("remove_item")
.click(function(){
$(this).parent().remove();
}));
但是,它找不到新创建的div标记。我也用javascript替换了它,但没有用。问题是它找不到新创建的div标记的id。如何解决它?见语法:
$("div#"+id).remove();
//Change to
$("#"+id).remove(); OR
$("div[id='"+id+"']").remove();
而不是$(“.remove_item”)。单击(function(){/*code*/}
使用$(“.remove_item”)。live('click',function(){/*code*/}
它们之间的差异首先可以在这里看到
new_compare_item = $("<div/>");
new_compare_item.attr("id", "compare_item");
new_compare_item.attr("name", "compare_item");
new_compare_item.addClass("div_image");
new_compare_item.append($("<img/>")
.addClass("image")
.attr("src", "/compare/sites/default/files/add_item.jpg")
.attr("height", 50)
.attr("width", 50));
new_compare_item.append($("<span/>")
.addClass("remove_item")
.click(function(){
$(this).parent().remove();
}));
$('body').append(new_compare_item);
不正确。应该是
});
而不是)}代码>。您应该使用.live('click',function(){})
而不是.click(function(){})
,因为您在DOM中动态添加了一个div。请参阅Div和span标记应为:$('')和$('')您有语法错误new\u compare\u项。追加($('')
-->缺少)
朋友请忽略此项)};我在进行相关更改时键入了错误的内容。$(“div#“+id).remove();工作正常。问题是它找不到新创建的div标记,或者准确地说,它找不到新创建的div标记的id。很抱歉,这是不正确的。当我在发布此问题时对代码进行更改时,我输入了错误的代码。谢谢你,我的声誉低于15,否则我也会给你评分:)
new_compare_item = $("<div/>");
new_compare_item.attr("id", "compare_item");
new_compare_item.attr("name", "compare_item");
new_compare_item.addClass("div_image");
new_compare_item.append($("<img/>")
.addClass("image")
.attr("src", "/compare/sites/default/files/add_item.jpg")
.attr("height", 50)
.attr("width", 50));
new_compare_item.append($("<span/>")
.addClass("remove_item")
.click(function(){
$(this).parent().remove();
}));
$('body').append(new_compare_item);
$(".remove_item").click(function(){
var id = $(this).parent().attr("id");
var remove_item_id = document.getElementById(id);
$("div#"+id).remove();
)};