2011-04-03 37 views
1

我有一個創建一個GridView的ASPX頁面。我的JQuery函數從Gridview數據中提取值來填充我的JQuery自動完成源。所有的工作都很好。現在我想讓自動完成值在點擊時進入鏈接。該鏈接也在Gridview中,我使用text()來獲取文本值。 (搜索我的包含「ModelDetail」和存儲文本到一個數組鏈接的GridView)我需要一個jQuery的2維數組?如果是這樣,我該怎麼做?這裏是我的代碼: JQuery的,ASP:GridView的和自動完成 - 爲自動完成需要鏈接值

<script language="javascript" type="text/javascript"> 
    $(document).ready(function() { 

     var modelnames = new Array(); 
     $('#ctl00_body_modellistGrid a[href*="ModelDetail"]').each(function() { 
      modelnames.push($(this).text()); 
     }) 


     $("input#autocomplete").autocomplete({ 
      source: modelnames 
     }); 

    }); 

</script> 

提前感謝! 鮑勃

+0

哪個自動完成插件您使用的?這個? http://docs.jquery.com/Plugins/autocomplete – Pandincus 2011-04-03 01:30:08

+0

@Pandincus - 看起來像jQuery UI – arma 2011-04-03 01:31:18

+0

@arma - 哦,我現在看到,原來的插件已棄用,以支持jQuery UI。謝謝! – Pandincus 2011-04-03 01:32:21

回答

1

的JavaScript處理任意對象非常漂亮 - 使用對象存儲文本和鏈接。

我的JavaScript是一個有點生疏,但這樣的事情應該工作:

var models = []; 
$('#ctl00_body_modellistGrid a[href*="ModelDetail"]').each(function(i) { 
    // Note that we're using the optional index parameter of the each function, 
    // which I have called 'i' 
    // We will create an object with a label and a value and store it in models[i] 
    models[i] = { label: $(this).text(), value: $(this).attr("href") }; 
}); 

// We will now pass this array of objects to the autocomplete function 
// The autocomplete function, if given an array of objects, is expecting 
// two properties: 'label' and 'value' 
$("input#autocomplete").autocomplete({ 
    source: models, 
    // We will also provide a function when the user selects an option 
    select: function(event, ui) { 
     // ui.item should hold the object we passed in, I think 
     // Let's redirect the user to the url 
     // ui.item.value should hold the url 
     window.location.href = ui.item.value; 
    } 
}); 

我相信上面的應該工作。我把一個非常基本的演示上的jsfiddle: - >http://jsfiddle.net/B3dgW/

+0

呵呵我也挖了我以前的PHP項目中,我使用的自動完成,你應該提供正常工作的代碼。如果autor不想更新數組創建部分,您仍然可以使用'ui.item.label'而不是'ui.item.value',因爲我可以使用select保存url的 – arma 2011-04-03 01:49:40

+0

@arma - 謝謝!很高興聽到我不是生鏽的。 ;-)你不必刪除你的答案 - 它會一樣正確。 – Pandincus 2011-04-03 01:51:18

+0

Na,你的答案更漂亮:D – arma 2011-04-03 01:53:27