简体   繁体   中英

How to add dynamically <li> tags in jquery list?

In the moment I can add li tags to my list with script. But how can I add dynamically li tags in a function in .js? Hopefully I will see a good example. Below is my code. Thanks!

<div data-role="page" id="searchPage" data-theme="b">
<div data-role="content">
    <ul data-role="listview" data-filter="true" data-theme="b" id="searchListUl">
    </ul>
</div>
<script type="text/javascript">
  $("#searchListUl").append('<li data-filtertext="Apple"><a href="#">Apple</a></li>');
  $("#searchListUl").listview('refresh');</script></div>

Your function would be something like:

var addItem = function(item){
    $("#searchListUl").append('<li data-filtertext="'+item+'"><a href="#">'+item+'</a></li>');
}

You can call it with: addItem("apple")

If you with "dynamic" mean that you want to be able to append list items without knowing the name ("Apple"), you could make a generic function, using the jQuery function used to create elements:

function add(name) {
    var $li = $("<li>").attr("data-filtertext", name)
                       .appendTo("#searchListUI");

    $("<a>").attr("href", "#")
            .text(name)
            .appendTo($li);
}

You could use it as follows:

<div data-role="page" id="searchPage" data-theme="b">
<div data-role="content">
    <ul data-role="listview" data-filter="true" data-theme="b" id="searchListUl">
    </ul>
</div>
<script type="text/javascript">
  add("Apple");
  $("#searchListUl").listview('refresh');</script></div>

It should be noted that using .append() in the way described in many of these answers will directly vulnerable to Cross Site Scripting (XSS) attacks. If strings are being pulled from a data source that can be influenced by users, then a user can put raw HTML, and when .append() is called, the raw HTML will get directly injected into the DOM. Script tags are especially dangerous. Once you can run arbitrary javascript in someones session, an attacker can grab their cookies, their private information, and even passwords in some circumstances, all without the victim knowing.

Always ALWAYS use .text() to set the text of an element. In jquery, .text() will properly HTMLEncode characters when it needs to. If you have experience with SQL, you can think of .append($RANDOM_STRING) the same way that you would think of conn.exec($RANDOM_STRING). By their very nature, they are vulnerable to injection and should be avoided at all costs.

I'm sure code from these examples have already been copied and pasted, and are now in use all over the internet, and that sucks. Please get the word out, .append() will append HTML, not just text, so improper use will let attackers inject raw HTML into your DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM