how to retrieve value from div
here is my html and jquery and when the page loads I'm supposed to get an alert box with the value 10 but instead i get nothing. what am I doing wrong?
<html>
<head>
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
val = $("#t").te开发者_JS百科xt();
alert(val);
</script>
</head>
<body>
<div id="t">10</div>
</body>
</html>
Try and always wrap your code to run when the document
has the elements populated, like this:
<script type="text/javascript">
$(function() {
val = $("#t").text();
alert(val);
});
</script>
...otherwise when $("#t")
runs to select id="t"
elements it does run...but the elements aren't in the DOM to find yet.
The HTML
<div id="t">10</div>
Is after the script, the script runs before finding nothing.
You have to change the order
<div />
<script />
Or use jQuery.ready
Example on jsBin
You are trying to retrieve something from an element that does not yet exist. The simplest solution is to move your JS code to the bottom of your HTML (right before the </body>
).
Another solution is to "wrap" your code inside a jQuery ready event:
$( document ).ready ( function () {
val = $("#t").text();
alert(val);
} );
The ready event will trigger when the DOM is ready to be manipulated with.
try this
<div id="t">10</div>
val = $("#t").html();
alert(val);
The script is executing before the div has been processed by the browser.
The div is not yet in the DOM.
You could either move the scrip tag to below the div or wrap you code in an on ready function:
<script type="text/javascript">
$(function () {
val = $("#t").text();
alert(val);
});
</script>
精彩评论