开发者

how to get an dom element into a variable with jquery?

I'm playing with a beginners tutorial about canvas

I was wondering if i can change this(which works straight from the tutorial):

     <script>  
        $(document).ready(function() {  
            var can = document.getElementById("myCanvas");  
            var ctx = canvas.getContext("2d");
            ctx.fillRect(50, 25, 150, 100);
        });  
    </script> 

into this:

 $(document).ready(function() { 
    can = $("开发者_如何学Cmycanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillRect(50, 25, 150, 100);
 }); 

or maybe even into

var ctx=$("mycanvas").getContext("2d");
ctx.fillRect(50,25,150,100);

something doesn't work and I can't figure out what? I tried adding .val() as i saw in countless articles

can=$("#mycanvas").val()

and also .atrr()

can=$("mycanvas").attr("id")

but to no avail what am i doing wrong? or maybe it isn't possible with jquery? I would be glad for any help with this.


It's .attr('id'), not .atrr('id').

To get the DOM node from a jQuery object, use the array subscript operator ([]) or the .get() method:

var can = $('#mycanvas')[0]; // or:
var can = $('#mycanvas').get(0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜