admin管理员组

文章数量:1390503

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.

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

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.

<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>
Share Improve this question edited Aug 3, 2017 at 4:17 dda 6,2132 gold badges27 silver badges35 bronze badges asked Jul 25, 2013 at 13:05 ChrisChris 472 gold badges2 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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

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

Demo: http://jsfiddle/DVbGY/1/

本文标签: javascriptDynamically add items to Listview in jQuery MobileStack Overflow