2010-05-24 36 views
0

如果列表是動態創建的,我如何獲得可選列表中項目的「id」?jquery ui selectable get id?

<ul id="selectable"> 
    <li id='1'>..</li> 
     . 
     . 
     <li... 
    </ul> 

我試圖var num = $('#selecable :selected').attr("option" , 'id');但只得到[對象的對象] ...

什麼是正確的方法是什麼?

+3

ID不能是數字,或者說可以」從他們開始,確保你的ID有某種類型的前綴,所以他們是有效的。 – 2010-05-24 19:12:45

+0

@Nick Craver好點,當我看到那個時候,我錯過了。 – ICodeForCoffee 2010-05-24 19:16:00

+0

您的「#selecable」有錯字 – 2010-05-24 19:17:07

回答

4

選擇的ID的名單將是:編輯:更好methinnks

$('#selectable').selectable(function(){ 
    selected:function(){ 
     var idlist = $(this).attr('id'); 
     //do something with the list...of id's 
    } 
}); 
+0

' :selected'不適用於'li'元素。 – 2010-05-24 19:21:00

+0

是的,我有一個腦抽筋,編輯愚蠢的東西:)當你評論。 – 2010-05-24 19:28:22

6

更新:

爲了完整,如果選擇的元素,該插件添加一個類ui-selected的元素。所以,你就可以用當前所選元素的ID:

$('#selectable .ui-selected').attr('id'); 

但要知道,多個元素可以選擇。


的jQuery UI的可選插件calls a callback whenever you select an element,你只需要提供它:

$("#selectable").selectable({ 
    selected: function(event, ui) { ... } 
}); 

這就是說,尼克已經提到,ID不能以數字開頭。

:selected只適用於option元素。

0
jQuery('#selectable').selectable(function(){ 
    selected: function(event, ui) 
    { 
    jQuery(".ui-selected", this).each(function() 
    { 
      var objID=jQuery(this).attr("id"); 
    }); 
    } 
}); 
5

此版本不需要特定的類名稱。使用$(ui.selected).attr('id')獲得(最後一個)選擇元素的ID:

$("#selectable").selectable({ 
    selected: function(event, ui) { 
     alert($(ui.selected).attr('id')); 
    } 
}); 
0
jQuery('#selectable').selectable(function() { 
    selected: function(event, ui) 
    { 
     alert(ui.selected.id); 
    } 
}); 
+0

你能否給出一些解釋和答案? – 2012-10-11 09:15:49

0

檢查這個..

$(".ui-selected", this).each(function() { 
    var index = $("#selectable li").attr(id); 

    }); 
-1
<script> 
$(function() { 
    $("#selectable").selectable({ 
     selected: function() { 
      var id = $(".ui-selected", this).attr("id"); 
      //alert(id); 
     } 
    }); 
}); 

+0

這不回答這個問題。 – 2014-06-28 00:15:58

+0

感謝羅布,我修改了答案。 – inquisitive 2014-06-28 00:41:06

+1

你可能想解釋一下你的答案。 SO不只是回答問題,而是教導人們事物的運作方式。 – Machavity 2014-06-28 00:57:10

相關問題