2012-12-01 54 views
4

我有一個問題,當使用jQuery克隆時,試圖將jQuery AutoComplete應用於表中的多行。 AutoComplete在第一行工作,但在將其他行添加到表時失敗。到目前爲止,我有以下幾點:JQuery AutoComplete和Clone

HTML表:

<table class="table" cellspacing="0" id="myTable"> 
     <tr> 
     <th width="40%">Item</th> 
     <th width="60%">Description</th> 
     </tr> 
     <tr> 
     <td>input name="product_title" id="product_title" type="text"><td> 
     <td><textarea name="product_description" id="product_description"></textarea></td> 
     </tr> 
    </table> 
    <input type="button" value="Add Row" onclick="javascript:addRow()"> 

克隆腳本:

function addRow(){ 
    $('#myTable tr:last').clone(true).insertAfter('#myTable tr:last'); 
    $('#myTable tr:last input').val(""); 
    $('#myTable tr:last input:first').focus();   
} 

自動完成腳本:

$().ready(function() { 
    $("#product_title").autocomplete(products, { 
    width: 380, 
    matchContains: "word", 
    formatItem: function(row) { 
     return row.title; 
    } 
    }); 
    $('#product_title').result(function(event, data) { 
    $('#product_description').val(data.description); 
    }); 
}); 

爲自動完成數據從拉一個簡單的MySQL查詢,它定義了產品標題和描述。

目前,添加新行可以正常工作,對於表的第一行AutoComplete也會正常工作,但是無法在添加的任何其他行上工作。即使我手動添加第二行到HTML表格,AutoComplete也無法在此上工作。

有沒有人知道是否有一個(簡單)的方法來修改上述代碼,使其工作?當談到jQuery時,我是新手,所以越詳細,越好。

在此先感謝!

回答

3

這是一個在動態添加元素上使用插件的常見問題。插入DOM後,通常需要在新元素上調用插件。除了爲初始頁面加載元素和新元素複製相同的代碼外,通常可以創建一個簡單的輔助函數,該函數使用父元素作爲主引用,並僅在該元素中搜索要應用該插件的元素。

重要事項:根據定義,當您克隆新行並且ID在頁面中必須唯一時,您正在重複ID。下面的代碼將你的ID改爲class,你需要在你的標記中做同樣的事情。

var $table; 
$(function() { 
    $table=$('#myTable'); 
    var $existRow=$table.find('tr').eq(1); 
     /* bind to existing elements on page load*/ 
     bindAutoComplete($existRow); 
}); 

function addRow(){ 
    var $row=$table.find('tr:last').clone(true); 
    var $input=$row.find('input').val(""); 
    $table.append($row); 
    bindAutoComplete($row); 
    $input.focus(); 

} 


function bindAutoComplete($row){ 
    /* use row as main element to save traversing back up from input*/ 
    $row.find(".product_title").autocomplete(products, { 
     width: 380, 
     matchContains: "word", 
     formatItem: function(row) { 
      return row.title; 
     } 
    }); 
    $row.find('.product_title').result(function(event, data) { 
     $row.find('.product_description').val(data.description); 
    }); 
} 
+0

嗨Charlietfl。非常感謝您的詳細回覆,這對我幫助很大!我改變了我的輸入字段,讓class =「product_title」和class =「product_description」,並且我還將我的代碼更改爲上面的代碼。 AutoComplete現在適用於所有新添加的字段,但唯一的問題是,當我在新添加的行中鍵入產品標題時,產品說明會在所有行上發生變化。你知道這可能是什麼原因嗎?再次感謝! – mckeegan375

1

Charlietfl的帖子解決我的問題,我不得不做出了更換唯一的變化:

var $row=$table.find('tr:last').clone(true);

var $row=$table.find('tr:last').clone();去除true

希望這有助於別人:)

1

我認爲問題是,與clone(),你克隆的元素,它已經擁有了自動完成屬性,然後自動完成不能以新的元素「再次」加。我覺得你不應該clone(),你應該使用元素的原始HTML代碼,並把它放在

編輯:

我如何固定它:

  1. autocomplete("destroy")爲原單輸入字段你想克隆。
  2. 克隆你的元素,並自動完成添加到它

,不使用clone(true),但你可以使用clone()