2014-02-17 38 views
0

我想知道,如何創建選擇器,鏈接到動態創建的元素,而不使用動態創建的元素上的事件?如何創建選擇器,鏈接到動態創建的元素?

注:動態創建的元素我的意思是元素,是不是在HTML開頭

我知道,我可以用$(本),當我有事件(例如。點擊)的元素,但是當我沒有事件,我需要動態創建的元素選擇器?

感謝所有。

更新:這裏是我的情況:

$(".product div a").click(function() { 
      var nameOfProduct = $(this).parent().find("h3").text(); 
      var dataPrice = parseInt($(this).parent().find("div b").text()); 
      var isProductIn = false; 
      var itemsInDay = $(/*HERE I NEED THE SELECTOR*/).find("div.item").nextUntil("div.center"); 

      itemsInDay.each(function() { 
       if (nameOfProduct == ($(this).find("span ins span").text())) {isProductIn = true;}; 
      }); 

      if (isProductIn) { 
       //add only +1, not new product again; 
      } else { 
       var imgOfProduct = $(this).parent().parent().find("img").attr('src').replace('med', 'min'); 
       var product = ('<div class="item" data-price="' + dataPrice + '"><img src="' + imgOfProduct + '"><span><ins><b>1x</b> ' + nameOfProduct + '</ins><a href="#"><img src="images/delete.png"></a></span></div>'); 
       $(product).appendTo(".dayOrder:last").delay(800).hide().slideDown(); 
      } 
      return false; 
}); 
+1

如何創建動態創建的元素?一些代碼? – dfsq

+1

在創建元素時爲元素分配變量,然後可以繼續使用它來操作元素。 –

+0

你爲什麼需要這種行爲?你最好告訴你在找什麼,爲什麼你需要'動態'選擇器?! –

回答

1

試試這個禮http://jsfiddle.net/pEb7D/5/

HTML:

<div class="test"></div> 

的Javascript:

dynamicSelector = $('.test').append('<div class="newElement">Hello!</div>'); 

setTimeout(function() { 
    dynamicSelector.text('Goodbye!'); 
}, 3000); 

UPDATE: 好吧,所以你要把物品放入.orderDay:last元素。在那裏你可以遍歷它的內容,看看你是否已經有一個或其他類型的現有元素。

但是,我會建議根據產品ID製作一個數組,然後對此作出反應。 例如http://jsfiddle.net/8byQp/

的Javascript:

daysOrderArray = [];  
$(".product div a").click(function() { 
      var nameOfProduct = $(this).parent().find("h3").text();    
      var imgOfProduct = $(this).parent().parent().find("img").attr('src').replace('med', 'min'); 
      var dataId = $(this).parent().parent().data("id"); 
      var dataPrice = parseInt($(this).parent().find("div b").text()); 
      priceSum += dataPrice; 
      updatePrice(priceSum); 

      if(dataId in daysOrderArray){ 
       // Now add number rather than new product. 
       daysOrderArray[dataId]++; 
       $('.item[data-id="' + dataId + '"] .quantity').text(daysOrderArray[dataId]); 

      } else { 
       daysOrderArray[dataId] = 1; 
      var product = ('<div class="item" data-id="' + dataId + '" data-price="' + dataPrice + '"><img src="' + imgOfProduct + '"><span><ins><b><span class="quantity">1</span>x</b> ' + nameOfProduct + '</ins><a href="#"><img src="images/delete.png"></a></span></div>'); 
      $(product).appendTo(".dayOrder:last").delay(800).hide().slideDown(); 
      return false; 
      } 
     }); 
+0

+1讓我們看看是否是這樣。 – Shomz

+0

這可能對我有幫助,但是你能否專門針對我的情況寫下你的建議? – user3294950

+0

你能專門針對你的情況寫下你的問題嗎?我看不到動態創建的元素在哪裏,它是如何創建的,我看不到它是什麼html? –