jquery append var
If i alert x i开发者_JS百科 can see the value. But from the below code, i can't seem to append the value to #result. What am i doing wrong.
<div id="result"></div>
<button id="more">more</button>
<script type="text/javascript">
var x = 'abcde';
var y = x.substring(0,2);
$('#more').click(function(){
$('#result').append(x);
});
</script>
Edit: Oops, your code works. I should've tested it, my bad. +1 to SLaks
You need to put your code inside $(document).ready(function() { });
. Read here to find out why.
<a href="#" id='more'>More</a>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function() {
var x = 'abcde';
var y = x.substring(0,2);
$('#more').click(function(){
$('#result').append(x);
});
});
</script>
W/o document ready - http://jsfiddle.net/Z2EjD/ -
<a href="#" id="more">More</a>
<div id="result"></div>
<script type="text/javascript">
var addToMore = function addToMore() {
var x = 'abcde';
var y = x.substring(0,2);
$('#result').append(x);
}
$("#more").click(addToMore);
</script>
That might be able to be improved. If anyone notices something, please comment.
If we are to go on this code sample alone then the answer is "You don't have an element with the id 'more' to click on".
That said, you've probably got an overly reduced test case that doesn't show that said element appears after the <script>
element, so doesn't exist when the script runs and tries to assign the event handler.
精彩评论