Jquery Error: $("[data-weight]") is null
Stripped a ton of stuff to make it more readable, it throws an error on the line:
$('[data-weight]').each(function() {
Saying that it is null
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="htt开发者_运维百科p://www.w3.org/1999/xhtml" >
<head id="ctl00_mainHead">
<script type="text/javascript" src="includes/jqueryv1.4.2.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('[data-weight]').each(function() {
var usingMetric = false;
var $this = $(this);
var value = $this.attr("data-weight");
if (usingMetric) {
$this.text(value + " KG");
}
else {
value = parseFloat(value) * 2.20462262; // Convert to imperial
$this.text(value + " lbs");
}
});
});
</script>
</head>
<body>
<form name="aspnetForm" method="post" action="viewProduct.aspx?ID=3&action=added" id="aspnetForm">
<div class="productDetail">
<b>Product Details</b>
</div>
<strong data-weight="200">800 KG</strong>
</form>
</body>
</html>
Update
It's a follow on my this question:
Using Javascript to display weights
If you're using jQuery's "no conflict" mode, the problem might be this:
jQuery(document).ready(function() {
^-- Consider adding $ here
...or use jQuery
rather than $
throughout.
If you're not using jQuery no-conflict, I'm not seeing why there'd be a problem. It works just fine here: http://jsbin.com/odaxa3 The only edits I made were to load jQuery from Google's CDN and to make the weight in the attribute match the display.
data-weight
is not a valid attribute, on before HTML5. How about doing it this way,
html part,
<strong class="weight-800">800 KG</strong>
jQuery part,
jQuery(document).ready(function () {
$('[class^="weight"]').each(function () {
var usingMetric = false;
var $this = $(this);
var value = this.className.split('-')[1];
if (usingMetric) {
$this.text(value + " KG");
}
else {
value = parseFloat(value) * 2.20462262; // Convert to imperial
$this.text(value + " lbs");
}
});
});
demo
Instead of converting the units, you could print all units and only display the one that is preferred:
<strong><span class="metric">800 kg</span> <span class="units-separator">/</span> <span class="imperial">1763 lbs</span></strong>
Now you can switch between the units by displaying/hiding the elements with the class metric/imperial:
.units-separator { display: none }
/* for metric view */
.metric { }
.imperial { display: none }
/* for imperial view */
.metric { display: none }
.imperial { }
And if CSS is not supported, both units are shown as:
800 kg / 1763 lbs
May i know,what is 'data-weight' ? Is it a control ID? If it is control id then you need to give :
$('#data-weight').children().each(function() {...
Or
The following post might be helpful to you :
jQuery attribute selectors: How to query for an attribute with a custom namespace
精彩评论