我有一个可选按钮列表,其名称是通过读取JSON文件动态生成的。每次点击一个按钮,我都想得到它的标题,即行[" name"]。这是我的相关代码和JSON:
<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"
},
],
}
这是有效的,因为我得到了格式的可选择列表:
<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>
当我点击第一个按钮时,我想获得值&#34; ABC&#34;。我不知道该怎么做。我读过.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>
答案 0 :(得分:1)
我认为这就是你要找的东西
selected: function() {
$( ".ui-selected", this ).each(function() {
alert($(this).text());
});
}
});
答案 1 :(得分:1)
$('#selectable').on('click', 'li', function(evt){
var text = $(this).text();
console.log(text);
});
解释这是如何工作的,它将click事件附加到列表项的父级,在您提供的代码中为#selectable
。将事件绑定到父元素会将一个事件附加到DOM 总计,而不是为每个列表项附加事件,因此它非常有效。这个概念称为事件委托。
on()
内显示的功能使用$(this)
选择器,可确保您获取仅被点击的项目文本。
答案 2 :(得分:0)
你可以这样做:
$('.ui-widget-content').click(function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});
DEMO:https://jsfiddle.net/lmgonzalves/pqo1r96p/
编辑:
请尝试这种方式:
$('body').on('click', '.ui-widget-content', function(){
var text = $(this).text(); // this get the text
alert(text); // do whatever you want with it
});