在jQuery Mobile中动态创建的可折叠集

Dynamically created collapsible-set in jQuery Mobile

本文关键字:可折叠 创建 动态 jQuery Mobile      更新时间:2023-09-26

好吧,一旦我看到这个问题的答案,我会觉得自己很愚蠢。 我确信这一点。

我已经完全按照我以前想要的方式创建了它,但我现在正在为新版本重构我的代码。 我正在尝试在jQuery Mobile中动态创建可折叠集,但我的html无法正确呈现。

  <div data-role="header">
        <h2>Playground</h2>
    </div>
    <div data-role="content">
        <div data-role="button" id="addprimary" data-inline="true">Add 5</div>
        <div data-role="collapsible">             
            <h4>Collapsible</h4> 
            <form id="makecollapsible">
            </form>
        </div>
    </div>
    <div data-role="footer">
        <h4>Please, no applause</h4>
    </div>
</div>
<script>
$('#addprimary').on('click', function () {
    Markup.Collapsible();
});
var Markup = new Object();

Markup.Collapsible = function () {
$('#makecollapsible')
.append($('<div>')
    .attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
 );
for (i = 0; i < 5; i++) {
    ($('<div>')
         .attr({ 'data-role': 'collapsible', 'data-content-theme': 'c', 
              'data-collapsed': 'true' })
         .html('<h4>' + i +'</h4>'))
    .appendTo('#primary');
   }
}
</script>

有人可以看看这个 http://jsfiddle.net/c2jLY/,告诉我我做错了什么吗? 我的<div> data-role='collapsible'没有呈现为可折叠对象,这也对我稍后尝试放入其中的 HTML 产生了影响。

感谢帮助,谢谢!

Markup.Collapsible在函数内部和末尾添加以下内容。对于可折叠集,你需要告诉jQM你正在增强一个.collapsibleset(),并将其与.trigger('create')结合起来。

$('#makecollapsible').collapsibleset().trigger('create');

演示


我忘了提到,当动态附加项目时,在父元素上调用增强方法;这样做,将增强子元素。因此,无需对追加的每个可折叠对象使用.collapsible().trigger('create')

我在这里展示的很简单,但可以工作:

<script type="text/javascript">
//dynamically make 10 collapsible items and append them to the collapsible-set
var jj = "SUPER item added..";
$('[data-role="content"]').append('<div id="set" data-role="collapsible-set"></div>');
var count;
	for (count=0; count < 10; count++) {  // div id should be from id='c0' to 'c9'
		$("#set").append('<div id="c' + count + '" data-role="collapsible">');
		$("#c" + count.toString()).append('<h3>Adding element_' + count +'</h3>');
		$("#c" + count.toString()).append(jj + 'count ' + count + '</div>');
	}
// either one is tested working below:
//		$('[data-role="content"]').trigger('create');
		$( "#set" ).collapsibleset( "refresh" );
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
	<!------------------------page 1 ListView template-->
		<div data-role="page"  id="page01">
		<div data-role="header" data-theme="b" data-position="fixed">			
			<h2>-- DEMO -- &nbsp;&nbsp;</h2>
		</div>
		<div data-role="content"  id="content">
  
    </div>
</body>