[英]how to add data to a dynamically added div?
I'm trying to prepend data to my dynamically added div - here is my code - 我想前置数据到我的动态添加的div - 这里是我的代码 -
<script type="text/javascript">
var addedDiv=0;
$(document).on("submit",".postFromAdd",function(event){
event.preventDefault();
var tmp = "#addedDiv"+addedDiv;
$("#showPostedData").prepend("<div id="+ tmp +"></div>");
// tmp having the id of my dymanically added div ,
//now I want to add some data to this div
//i did like --
$(tmp).prepend("<p>Dynamic data here</p>");
addedDiv++;
});
</script>
but $(tmp).prepend("<p>Dynamic data here</p>");
但是
$(tmp).prepend("<p>Dynamic data here</p>");
not working . 不起作用。 how can i fix it ?
我该如何解决?
remove id selector # from variable. 从可变除去id选择#。
var tmp = "addedDiv"+addedDiv;
$('#'+tmp).prepend("<p>Dynamic data here</p>");
Your selectors are the problem, since the tmp
is assigned as the id don't prefix it with #
add the id selector when you use it as an selector. 您的选择器是问题所在,因为
tmp
被分配为ID,在您将其用作选择器时,请不要使用#
添加ID选择器作为前缀。
var addedDiv = 0;
$(document).on("submit", ".postFromAdd", function (event) {
event.preventDefault();
//no # here
var tmp = "addedDiv" + addedDiv;
$("#showPostedData").prepend("<div id=" + tmp + "></div>");
//add # here
$('#' + tmp).prepend("<p>Dynamic data here</p>");
addedDiv++;
});
Updated Code 更新的代码
<script type="text/javascript">
var addedDiv=0;
$(document).on("submit",".postFromAdd",function(event){
event.preventDefault();
var $div=$('<div/>',{'id':'#addedDiv'+addedDiv});
$div.prepend("<p>Dynamic data here</p>");
$("#showPostedData").prepend($div);
addedDiv++;
});
</script>
$('#'+tmp).html('<p>you can ad text or html here</p>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.