Reputation: 283
I'm learning the use of Data-* attribute in HTML5 and JQuery, about How to retrieve data simply from a div.
This is my markup:
<!DOCTYPE html>
<html >
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="../Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$('#restoreButton').click(function () {
var sources$ = $('div').data('module');
});
});
</script>
<div data-module="Sources" data-module-id="sourcePane">
<button type="button" class="green90x24" id="restoreButton">Restore</button>
</div>
</body>
</html>
It says the variable sources$ is Undefined
.
I am using simple data() function of JQuery, but doesn't work. I've seen this is one of the Basic.
Any suggestion would be helpful
Upvotes: 1
Views: 904
Reputation: 25081
The .data
method in jQuery 1.4.1 cannot be used with HTML data attributes. You need jQuery 1.4.3 (minimum) instead.
The example page you are working from, http://bibeault.org/jqia2/chapter3/lab.move.and.copy.html does not use the .data
method to retrieve the value of data-module
.
If you check the source, there's another external script, jqia2.support.js, which retrieves the value of data-module
using the .attr
method (which is the workaround for working with HTML data attributes in jQuery 1.4.1). See lines 50 and 55 for this:
$(this).attr('data-module')
Here's a fiddle: http://jsfiddle.net/3dP6A/
Upvotes: 0
Reputation: 584
it says the variable sources$ is Undefined .
Wherever it says so, it most definitely means you are trying to access sources$ from outside it's scope. You cannot access it outside the anonymous function you are defining as click callback.
Upvotes: 0
Reputation: 22674
Your code works but you are probably not loading jQuery properly. Check the the source URL of your jQuery script and make sure it loads. Also is there a reason you are adding the $
sign at end if the variable sources$
? It's uncommon.
Upvotes: 0
Reputation: 1
Existing piece from original post appear to work ok, utilizing jQuery 1.11.0
html
<div data-module="Sources" data-module-id="sourcePane">
<button type="button" class="green90x24" id="restoreButton">Restore</button>
</div>
js
$(function () {
$('#restoreButton').click(function () {
var sources$ = $('div').data('module');
$("body").append(sources$)
});
});
jsfiddle http://jsfiddle.net/guest271314/LZfUv/
Upvotes: 0
Reputation: 582
Where is the place to use this variable sources$?
You should to use this variable in the click event handler.
Or you should to define variable as global variable.
Upvotes: 0
Reputation: 582
Please check your version of jQuery.
Or check logs in developer tools (Ctrl+Shift+I in Windows, Command+Option+I in Mac).
You can check your variable sources$ with
console.log(sources$);
Upvotes: 1
Reputation: 13621
Might need to update your version of jquery, but also try:
$('div').data('module-id');
The data method grabs the attribute, expecting the key after data-
Upvotes: 0