如何在jQuery Mobile中动态设置'data-collapsed'和'data-theme'?

Jav*_*yer 3 javascript jquery jquery-mobile

我在运行时动态设置'data-theme'和'data-collapsed'时遇到问题,我用过:

$(selector).attr('data-collapsed',false) 
Run Code Online (Sandbox Code Playgroud)

$(selector).attr('data-theme',b) 
Run Code Online (Sandbox Code Playgroud)

但它不起作用,如何使用jQuery或javascript解决这个问题?

Phi*_*ord 5

你可以使用pagebeforecreate事件

请注意,通过绑定到pagebeforecreate,您可以在jQuery Mobile的默认窗口小部件自动初始化之前操作标记.例如,假设您要通过JavaScript而不是HTML源添加数据属性,这就是您要使用的事件.

例:

JS

$('#home').live('pagebeforecreate',function(event) {
    var col = $('#collapseMe');

    // Alternative settings
    //col.attr('data-collapsed','false');
    //col.attr('data-theme','b');

    col.data('collapsed',false);
    col.data('theme','b');
});
Run Code Online (Sandbox Code Playgroud)

HTML

<!DOCTYPE html>
<html class="ui-mobile-rendering">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mobile: Demos and Documentation</title>
    <link rel="stylesheet"  href="http://jquerymobile.com/test/css/themes/default/jquery.mobile.css" />

    <script src="http://jquerymobile.com/test/js/jquery.js"></script>
    <script src="http://jquerymobile.com/test/js/jquery.mobile.js"></script>

</head>
<body>
<div data-role="page" id="home">
    <div data-role="content">
        <div data-role="collapsible" data-theme="a" data-content-theme="a" id="collapseMe">
           <h3>Header swatch A</h3>
           <p>I'm the collapsible content with a themed content block set to "A".</p>
        </div>
    </div>
</div>
</body>
</html>
?
Run Code Online (Sandbox Code Playgroud)