jQuery 在jquery mobile中将<li/>动态添加到<ul/>

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

Dynamically adding <li/> to <ul/> in jquery mobile

jqueryhtmljquery-mobile

提问by locoboy

I'm trying to add list items to unordered lists in jquery mobile, but the formatting doesn't seem to be created properly.

我正在尝试将列表项添加到 jquery mobile 中的无序列表,但格式似乎没有正确创建。

<ul data-role="listview" data-theme="c" data-dividertheme="b">
                    <li data-role="list-divider">
                        Title Divider
                    </li>
                    <li>
                        <a href="test.html" data-transition="slide">List item 1</a>
                    </li>

 </ul>

Script:

脚本:

$('ul').append('<li><a>hello</a></li>');

For some reason the li generated dynamically doesn't display the same way as the one that's statically created. Does anyone know why and how I can make it the same?

出于某种原因,动态生成的 li 与静态创建的 li 显示方式不同。有谁知道为什么以及如何使它相同?

回答by thecodeparadox

Try this:

尝试这个:

$('ul').append($('<li/>', {    //here appending `<li>`
    'data-role': "list-divider"
}).append($('<a/>', {    //here appending `<a>` into `<li>`
    'href': 'test.html',
    'data-transition': 'slide',
    'text': 'hello'
})));

$('ul').listview('refresh');

回答by naugtur

The answers provided turned out to be a little bit messy...

结果发现提供的答案有点乱......

$('ul').append('<li><a>hello</a></li>');is ok, but it needs to refresh the listview, so all you need is:

$('ul').append('<li><a>hello</a></li>');没问题,但它需要刷新列表视图,所以你需要的是:

$('ul').append('<li><a>hello</a></li>').listview('refresh');

回答by Sandeep Taneja

And if you want to change the attributes of UL, you might have to call .trigger('create') for the enclosing div. this ensures that UL is created again with properties reset.

如果您想更改 UL 的属性,您可能必须为封闭的 div 调用 .trigger('create') 。这可确保在重置属性的情况下再次创建 UL。

回答by Cyber Slueth Omega

Your <a> tag is not referencing a webpage.

您的 <a> 标签未引用网页。

try:

尝试:

$('ul').append('<li><a href="test2.html' data-transition="slide" />List Item 2</li>');

回答by thebugger

You will have to add a class to the list tag

您必须在列表标签​​中添加一个类

$('<ul>').append( $('<li>').attr('class','ui-li ui-li-static ui-btn-up-c ui-li-last').append('hello'))  ;

JQuery mobile automatically adds a class to the list items, which can be seen if you run your page in firefox and debug it using firebug. Select whatever class has been applied and add it to your dynamically generated li tag.

JQuery mobile 会自动向列表项添加一个类,如果您在 firefox 中运行您的页面并使用 firebug 对其进行调试,则可以看到该类。选择已应用的任何类并将其添加到动态生成的 li 标记中。