【问题标题】:Adding jQuery Mobile elements to a page after it loads?加载后将 jQuery Mobile 元素添加到页面?
【发布时间】:2013-04-03 19:32:08
【问题描述】:

在这个 jsFiddle 示例中...

http://jsfiddle.net/LFgSr/

...我正在尝试在页面加载后在 div 中添加 jQuery Mobile 样式的按钮。页面加载时出现在页面上的大按钮看起来很棒......但是当我尝试“动态”添加另一个外观相似的按钮(通过单击“添加另一个按钮”)时,它不会被设置为它应该是(即使我通过 jQuery 为按钮“附加”正确的 HTML 代码)。

这里是完整的代码...

<!DOCTYPE html>
<html>

<head>

    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>

</head>

<body>

    <!-- Mark-up -->

    <input id="addButton" type="button" value="Add Another Button">

    <div style="width: 300px; height: 400px; top: 50px; left: 10px; position: absolute; border: 1px solid black;" >
        <section id="page1" data-role="page">
            <div class="content" data-role="content">
            <a href="#" data-role="button">This is a button!</a>
            </div>
        </section>
    </div>

    <!-- Script -->

    <script>
        $(document).ready(function() {
            $('#addButton').click(function() {
                $('.content').append('<a href="#" data-role="button">This is another button!</a><br />');
            });
        });
    </script>

</body>
</html>

我在这里缺少什么?如何让 jQuery Mobile 识别这样的 HTML 动态更新?

谢谢!

【问题讨论】:

    标签: jquery jquery-mobile markup jquery-mobile-button


    【解决方案1】:

    这是一个工作示例:http://jsfiddle.net/Gajotres/2uerX/

    $(document).on('pagebeforeshow', '#index', function(){       
        $('#addButton').click(function() {
            $('.content').append('<a href="#" data-role="button">This is another button!</a><br />');
            $('[data-role="button"]').button();
        });
    });
    

    当您动态添加新的 jQM 内容时,jQM 还必须增强新内容。如果是按钮,则使用以下命令完成:

    $('[data-role="button"]').button();
    

    要了解更多信息,请查看我的其他答案/文章:jQuery Mobile: Markup Enhancement of dynamically added content

    【讨论】:

    • Gajotres... 我刚刚阅读了您的另一篇文章。非常有帮助!不过,如果您不介意,还有 1 个快速问题。假设我想增强整个页面,except 用于 1 个特定项目。例如......在我的 jsFiddle 示例中,我想增强大矩形 div(大按钮)中的所有内容,但我不想增强顶部的小按钮(#addButton)。我该怎么做?
    • 你会添加一个 data-role="none" 到那个按钮,这会阻止那个按钮的样式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2013-05-22
    • 2012-05-01
    • 2013-12-10
    • 2019-08-09
    • 2018-09-13
    相关资源
    最近更新 更多