简体   繁体   中英

How to create a button dynamically using jQuery Mobile?

I want to create a button dynamically using jQuery. Please note that I'm using jQuery 1.9.1, and jQuery Mobile 1.3.1. The button should have the following properties:

<button id="WPshare" onclick="window.plugins.socialsharing.share('Share this message', null, null, null)">Share</button>

I have the following HTML:

<div id="finalPage" data-role="page" data-add-back-btn="false">
            <div data-role="header" data-position="fixed" data-tap-toggle="false">
                <h1>Result</h1>
            </div>
            <div id="share" data-role="content">
                <ul data-role="listview" id="myTripView" data-inset="true" data-theme="d">
                    <li>
                        <a href="#home" data-transition="slide" style="font-size:14px;">Home</a>
                    </li>
                </ul>
            </div>
</div>

I want it to be created inside the div with the id "share", it should be just under the <ul> element. Any ideas how to achieve it?

Use jQuery after()

button = $('<button id="WPshare" onclick="window.plugins.socialsharing.share(\'Share this message\', null, null, null)">Share</button>');
$('#share ul').after(button);
button.button();

Demo Fiddle

button.button() is a jQuery mobile function for buttons. It gives a functional and JQM styled button.


Or .append()

var button = $('<button id="WPshare" onclick="window.plugins.socialsharing.share(\'Share this message\', null, null, null)">Share</button>');
$('#share').append(button);
button.button();

shaunakde answer will work but I think this way is more "clear" :

    $("<button>", {
                     'id' : "WPshare",
                     text: 'Share',
                     })
                    .on("click", function() {
                window.plugins.socialsharing.share(\'Share this message\', null, null, null)"
    }).appendTo("#share");

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