Jaxkr
Jaxkr

Reputation: 1284

Define hyphenated attribute with jQuery?

I'm making a test app using jQuery mobile and Phonegap. I have the following page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mobile: Theme Download</title>
    <script src="cordova-2.5.0.js"></script>
    <link rel="stylesheet" href="Longmont.min.css" />
    <link rel="stylesheet" href="jquery.mobile.structure-1.3.0.css">
    <script src="jquery.js"></script>
    <script src="jquery.mobile.js"></script>
    <script>
        document.addEventListener("deviceready", onDeviceReady, false);

        function onDeviceReady() {
            setTimeout(function() {
                       navigator.splashscreen.hide();
                       }, 500);
        }
    </script>
    <script>
    $(document).ready(function() {
        $.getJSON('http://localhost/api.php', {'id':3}, function(data) {
            var items = [];

            $.each(data, function(key, val) {
                items.push('<div data-role="collapsible"><h1>' + val + '</h1></div>');
            });

            $('<div/>', {
                data-role: 'collapsible-set',
                html: items.join('')
            }).appendTo('#page');

        });
    });
    </script>
</head>
<body>
    <div data-role="page" id="page">
    </div>
</body>
</html>

I'm trying to put the items array into a div with the data-role set to collapsible-content. So, I edit the attribute when creating it (in $('<div/>', {). However, this attribute is hyphenated, and when I try this code in the simulator it displays a blank page.

What is the proper way to represent a hyphenated attribute in jQuery?

Upvotes: 4

Views: 4821

Answers (3)

Omar
Omar

Reputation: 31732

To define attribute with hyphen, check this answer by Kevin B Define hyphenated attribute with jQuery?


To enhance collapsible markup, follow the methods below after appending the items into body.

For collapsible (reference)

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

For collapsible-set (reference)

$('[data-role=collapsible-set]').collapsibleset('refresh');

Upvotes: 5

Explosion Pills
Explosion Pills

Reputation: 191739

jQuery's data is not exactly analogous to dataset, nor should it be because that is not as widely supported as we'd like thanks to MS. data-role is invalid syntax, but dataRole does not work either even if you'd expect it to. You can either do:

"data-role": value

or

{data: {role: value}}

http://jsfiddle.net/ExplosionPIlls/dK8ak/1/

Upvotes: 1

Kevin B
Kevin B

Reputation: 95023

object properties that contain - must be wrapped in quotes.

"data-role": value

The same goes for other operators and special characters such as quotes, :, ;, spaces, etc.

Upvotes: 13

Related Questions