2013-07-16 23 views
2

我需要爲每個提交按鈕創建一個獨特的div和唯一的名稱 - 我是jQuery的新手 - 請幫助我。jQuery中的動態div

$(document).ready(function() { 
    done(); 
}); 

function done() { 
    setTimeout(function() { 
     updates(); 
     done(); 
    }, 200); 
} 

function updates() { 
    $.getJSON("fetch.php", function(data) { 
     $("ul").empty(); 
     $.each(data.result, function(){ 
      $("ul").append("<li>Item: "+this['item']+ 
       "</li><li>Price: "+this['price']+"<br />") 

      $("ul").append("<div id='a'><input type='submit' 
       style='position:relative;top:100px;'>" + "<br /></div>") 

     }); 

    }); 
} 
+0

那麼是什麼問題你有嗎? –

+0

一個JSFiddle或至少一個更透徹的解釋或標記的樣本將是有幫助的 – Calvin

+0

'我需要爲每個提交按鈕創建一個獨特的div和唯一的名稱爲什麼你需要一個獨特的div和按鈕..有可能如果你可以解釋你的問題,那麼更好的解決方案..你也試圖追加無效的'HTML' ..''ul'元素語義上應該包含'li'作爲他們唯一的直接的孩子.. –

回答

1

您可以使用當前日期時間

function generateRandomSuffix() { 
    return (new Date()).getMilliseconds().toString() 
} 

生成的ID的唯一後綴然後將其添加到您的ID

$("ul").append("<div id='a" + generateRandomSuffix() +"'><input type='submit' style='position:relative;top:100px;'>" + "<br /></div>") 
0

您可以創建一個計數器,並在每次迭代的div id,將計數器值附加到標記的相關元素。只要確保每次使用計數器時都會增加計數器的次數。快速僞例如:

$counter = 0; 
$("ul").append("/<div id='a"+$counter+"'><input type='submit' id='submit"+($counter++)+" style... 
0

在你的情況下,最好使用setInterval代替setTimeout, ,你可以這樣做:

$(document).ready(function() { 
     setInterval(function() { updates() }, 200); 
    }); 

var curid = 0; 
function updates() { 
    $.getJSON("fetch.php", function (data) { 
     var html = '<ul>'; 
     $.each(data.result, function() { 
      html += "<li>Item: " + this['item'] + "</li><li>Price: " + this['price'] + "<br />"; 
      html += "<input type='submit' style='position:relative;top:100px;'>" + "<br />"; 
     }); 
     html +='</ul>'; 

     curid += 1; 
     var box = document.createElement("div"); 
     box.id = "div" + curid; 
     box.className = "myclass"; 
     document.body.appendChild(box); 
     box.innerHTML(html); 
    }); 
} 
0

嘗試

var counter = 0; 
function updates() { 
    var $ul = $('ul'); 
    $.getJSON("fetch.php", function(data) { 
     $ul.empty(); 
     $.each(data.result, function(){ 
      counter++; 

      var $li = $('<li />'); 
      $li.append("<li>Item: "+this['item'] + '<br />'); 
      $li.append("Price: "+this['price'] + '<br />'); 

      $('<div />', { 
       id: counter 
      }).append('<input type="submit" style="position:relative;top:100px;"/>').a[appendTo($li) 

      $ul.append($li) 

     }); 

    }); 
}