SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Jquery object notation

    Hi,
    Can anyone explain me, why
    this code doesn't work, please ?

    Code HTML4Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title></title>
    <meta name="content-language" content="en" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
     
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
    var myJqueryTest = {
      $ref : $('#target1'),
      init: function(){
        console.log(typeof myJqueryTest.$ref);
        console.log(typeof $('#target2'));
        myJqueryTest.$ref.text('My test 1');
        $('#target2').text('My test 2');
      }
    }
    $(myJqueryTest.init);
    </script>
     
    </head>
    <body>
    <div id="target1"></div>
    <div id="target2"></div>
    </body>
     
    </html>

    Bye.

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That javascript is executed when the browser parses it. This is when the browser doesn't even know what's in the body yet. So it doesn't know about #target1. So you have to set your $ref bit within the init so that the browser tries to locate $target1 after the body has loaded (thanks to the $() function).

    Code javascript:
    var myJqueryTest = {
      init: function(){
        myJqueryTest.$ref = $('#target1');
        console.log(typeof myJqueryTest.$ref);
        console.log(typeof $('#target2'));
        myJqueryTest.$ref.text('My test 1');
        $('#target2').text('My test 2');
      }
    }
    $(myJqueryTest.init);

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks I forgot the basis


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •