我有一個可選按鈕的列表,其名稱是通過從JSON文件中讀取動態生成的。每次點擊一個按鈕時,我都希望得到它的標題,即行[「name」]。這裏是我的相關代碼和JSON:獲取jQuery中可選項目的標題
<head>
<script>
$.getJSON("json-data.txt",function(data){
var items = [];
$.each(data['data'],function(i, row){
items.push("<li class = 'ui-widget-content'>" + row["name"] + "</li>");
});
$("<ol/>",{
"id" : "selectable",
html : items.join("")
}).appendTo("body");
});
var selectableObj = {
selected: function(event, ui){
}
}
$(function() {
$("#selectable").selectable(selectableObj);
});
</script>
</head>
<body>
</body>
的JSON數據:
{
"data": [
{
"name": "ABC",
"visited" : "Yes"
},
{
"name": "DEF",
"visited" : "Yes"
},
{
"name": "GHI",
"locked": "No"
},
],
}
這工作,因爲我得到selectables列表格式:
<ol id="selectable">
<li class="ui-widget-content">ABC</li>
<li class="ui-widget-content">DEF</li>
<li class="ui-widget-content">GHI</li>
</ol>
當我點擊第一個按鈕,我想獲得「ABC」值。我不知道該怎麼做。我閱讀.text(),但不明白使用它。任何人都可以幫忙嗎?
編輯 - 基於一些意見,我改變了我這樣的代碼,但它不工作:
<script>
$(function() {
$("#selectable").selectable();
});
$.getJSON("json-data.txt",function(data){
var items = [];
$.each(data['data'],function(i, row){
items.push("<li class = 'ui-widget-content'>" + row["name"] + "</li>");
});
$("<ol/>",{
"id" : "selectable",
html : items.join("")
}).appendTo("body");
});
$('.ui-widget-content').click(function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});
</script>
有沒有辦法做到這一點動態,我的意思,而不是1,2等。使用我,爲ith按鈕? – user3033194
@ user3033194我認爲lmgonzalves的答案是你需要的..如果它不是..告訴我你想要做什麼 –
Imgonzalves的答案是正確的,但可選擇它不起作用,或者至少我不知道在哪裏把它放在selectableObj的代碼中。 – user3033194