javascript 在 jQuery Mobile 中将项目动态添加到 Listview

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17858885/
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 09:52:43  来源:igfitidea点击:

Dynamically add items to Listview in jQuery Mobile

javascripthtmljquery-mobile

提问by Chris

I'm having a bit of trouble dynamically adding items to a listview in jQuery mobile. Basically I want whatever is input by the user in the textbox to be added to the list. I have the following code and can not figure out why the desired output is not appearing.

我在 jQuery mobile 中将项目动态添加到列表视图时遇到了一些麻烦。基本上我希望用户在文本框中输入的任何内容都添加到列表中。我有以下代码,无法弄清楚为什么没有出现所需的输出。

<script>
  var listCreated = false;
  function appendToList() {
    if(!listCreated) {
      $("#items").append("<ul id='list' data-role='listview' data-inset='true'></ul>");
      listCreated = true;
      $("#items").trigger("create");
    }
    $("#list").append("<li>");
    $("#list").append(document.getElementById(item).value);
    $("#list").append("</li>");
    $("#list").listview("refresh");
  }
</script>
<div data-role="content">
  <div id="items"></div>
  <input type="text" id="item" />
  <input type="button" value="Add item to list" onclick="appendToList()"/>
</div>

采纳答案by tymeJV

Try creating the entire lithen appending, right now, you're appending an opening <li>to the list, then the value to the list, not the new li

尝试创建整个li然后附加,现在,您将一个开头附加<li>到列表中,然后将值附加到列表中,而不是新的li

var value = $("#item").val();
var listItem = "<li>" + value + "</li>";
$("#list").append(listItem);

Demo: http://jsfiddle.net/DVbGY/1/

演示:http: //jsfiddle.net/DVbGY/1/