javascript 如何通过单击按钮获取 UL / LI 框的选定 ID - Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21376243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the selected ID of a UL / LI Box by Clicking on a Button - Jquery
提问by Preprocezzor
I'm trying to get the Value of a Listbox made of li via button Click. I searched the web but the most solutions are with the onClick button on the listbox itself. I tried something like this.
我正在尝试通过单击按钮获取由 li 组成的列表框的值。我在网上搜索,但大多数解决方案是使用列表框本身上的 onClick 按钮。我试过这样的事情。
Listbox:
列表框:
echo("</head><body><ul id='selectable'>");
while($satz != null)
{
echo "<li class='ui-widget-content' id='userid' value='$satz[ID]'>$satz[username]</li>";
$satz=mysql_fetch_assoc($cursor);
}
echo("</ul></body></html>");
JQuery:
查询:
$(document).ready(function()
{
$("#del").click(function()
{
var id = document.getElementById('selectable li').value;
alert(id);
But ID is undefined, what to do? Thanks.
但是ID未定义,怎么办?谢谢。
采纳答案by undefined
ul
element doesn't work like the select
element, ie it doesn't have a selected option(value). That's why other solutions suggest listening to the click event of the li
elements. You should either use a select
element instead of the ul
element:
ul
元素不像元素那样工作select
,即它没有选定的选项(值)。这就是为什么其他解决方案建议监听li
元素的点击事件。您应该使用select
元素而不是ul
元素:
$("#del").click(function() {
var id = $('#selectable').val();
});
Or add an identifier like a specific className to the target li
element:
或者向目标li
元素添加一个像特定 className 这样的标识符:
$("#del").click(function() {
var id = $('#selectable li.selected').attr('value');
});
That being said please note that your markup is invalid because:
话虽如此,请注意您的标记无效,因为:
- You are using the same ID for several elements, IDs are supposed to be unique. Here classes should be used instead.
value
is not a valid attribute for theli
element, you should usedata-*
attributes instead. Then you can read the values using jQuery.data()
method. Supposing you have adata-value
attribute for reading the value, you can code:$('#selectable li.selected').data('value')
.- You are generating
body
element with it's contents and also including another page.
- 您对多个元素使用相同的 ID,ID 应该是唯一的。这里应该使用类。
value
不是li
元素的有效属性,您应该改用data-*
属性。然后您可以使用 jQuery.data()
方法读取值。假设您有一个data-value
用于读取值的属性,您可以编码:$('#selectable li.selected').data('value')
.- 您正在生成
body
元素及其内容,还包括另一个页面。