2012-12-06 51 views
0

我正在執行jQuery插件Tag-it!的產品輸入表單,用於將屬性分配給不同類型的產品(筆記本電腦,電視機,小配件等)。jQuery - 如何調用/綁定jQuery事件添加ajax元素?

概念如下: 添加新產品時,首先,用戶從下拉列表中選擇要添加的產品的產品類別,然後觸發jQuery.change()事件,使ajax調用獲取所有產品與該類別相關的屬性。例如,如果我添加一臺電視,我希望我的ajax調用爲英寸,面板類型,hdmi填充3個輸入,而如果我添加一臺筆記本電腦,我希望這些輸入是cpu,ram,hdd,screen等Tag-它!與單詞列表(在我的情況下,屬性)和用於選擇單詞集的輸入字段一起工作。 在我的情況下,對於每種類型的屬性,我想填充一個單獨的輸入字段並將其分配/綁定到/應用tagit插件(對不起,我不知道如何解釋它)。

使用Javascript:

<script src="../js/tag-it.js" type="text/javascript" charset="utf-8"></script> 
<script> 
     $(function(){ 
      // Sample1: var sampleTags1 = ["red", "green", "blue"]; 
      // Sample2: var sampleTags2 = ["lcd", "plasma", "tft"]; 

      var sampleTags1 = [<?=createTags('name', 'tags', 1)?>]; 
      // createTags($name, $tags, $id) is a PHP function that returnss a list of tags for a given attribute 
      // Question 1: how do I place this here after a new input is added to the DOM? 
      $('#myTags').tagit(); 

      //Question 2: for each input added to the DOM I need also to add this block in the javascript: 
      $('#allowSpacesTags1').tagit({itemName: 'item1', fieldName: 'tags1', 
       availableTags: sampleTags1, allowSpaces: true 
      }); 

      $('#removeConfirmationTags').tagit({ 
       availableTags: sampleTags, 
       removeConfirmation: true 
      }); 
     }); 

$(document).ready(function() { 
    $('#cat_id').change(function(){ 
     $.post('../includes/ajax.php', { 
      cat_id : $(this).find("option:selected").attr('value')}, function(data) { 
      $("#tagholder").html(data); 
     }); 
    }); 
}); 

</script> 

Ajax的返回每個呼叫以下:

<ul id="allowSpacesTags'.$row['ctid'].'"></ul> // $row['ctid'] is the ID for that attribute 

其表示用於輸入標籤/屬性的輸入欄。

在出現任何誤解之前,我並沒有問如何在PHP中這樣做。 我的問題是關於我可以動態添加類似sampleTags1的var的方法,並且還爲每個由ajax添加到DOM的新輸入調用tagit()。如果我的問題不夠清楚,我會嘗試提供所需的任何信息。 請看代碼註釋中的問題。謝謝!

+1

看一看在()方法http://api.jquery.com/on/ –

+0

恐怕我沒有線索將它添加到我的代碼中。你能舉一個小例子讓我開始嗎? – bikey77

回答

1

http://api.jquery.com/live/

與.live(事件處理程序(eventObject)傳遞) 你不需要附加或內容時動態添加

編輯 我剛剛notticed是重新連接事件生活已被棄用,而應該使用

。對() http://api.jquery.com/on/

+0

是不是live()已被棄用? – bikey77

+0

humm,它實際上是,我不知道,在jquery的網站上,它建議你寧願使用.on() –

相關問題