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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:46:35  来源:igfitidea点击:

How to get the selected ID of a UL / LI Box by Clicking on a Button - Jquery

javascriptjqueryhtmllistbox

提问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

ulelement doesn't work like the selectelement, ie it doesn't have a selected option(value). That's why other solutions suggest listening to the click event of the lielements. You should either use a selectelement instead of the ulelement:

ul元素不像元素那样工作select,即它没有选定的选项(值)。这就是为什么其他解决方案建议监听li元素的点击事件。您应该使用select元素而不是ul元素:

$("#del").click(function() {
   var id = $('#selectable').val();
});

Or add an identifier like a specific className to the target lielement:

或者向目标li元素添加一个像特定 className 这样的标识符:

$("#del").click(function() {
   var id = $('#selectable li.selected').attr('value');
});

That being said please note that your markup is invalid because:

话虽如此,请注意您的标记无效,因为:

  1. You are using the same ID for several elements, IDs are supposed to be unique. Here classes should be used instead.
  2. valueis not a valid attribute for the lielement, you should use data-*attributes instead. Then you can read the values using jQuery .data()method. Supposing you have a data-valueattribute for reading the value, you can code: $('#selectable li.selected').data('value').
  3. You are generating bodyelement with it's contents and also including another page.
  1. 您对多个元素使用相同的 ID,ID 应该是唯一的。这里应该使用类。
  2. value不是li元素的有效属性,您应该改用data-*属性。然后您可以使用 jQuery.data()方法读取值。假设您有一个data-value用于读取值的属性,您可以编码: $('#selectable li.selected').data('value').
  3. 您正在生成body元素及其内容,还包括另一个页面。