SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2008
    Location
    Taiwan
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [jQuery] inline-defined functions doesn't work with $.noConflict()

    When creating a new element by using HTML string, we can define a function inline so that we don't have to write another line of javscript code to bind the function to the element. It is very convenient.

    For example:
    Code:
    <html>
    <body>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
    
    $('body').prepend('<a onclick="welcome()">click</a>');
    
    function welcome() {
    	alert("Hi, welcome!");
    }
    
    </script>
    
    </body>
    </html>
    However, if there is another javascript library being used on the same page, we will have to use jQuery's $.noConflict() to relinquish jQuery's control of the $ variable.

    In such situation, the inline-defined function doesn't work.

    Code:
    <html>
    <body>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script type="text/javascript">
    
    $.noConflict();
    
    jQuery(document).ready(function($) {
    
    	$('body').prepend('<a onclick="welcome()">click</a>');
    	
    	function welcome() {
    		alert("Hi, welcome!");
    	}
    
    });
    
    </script>
    
    </body>
    </html>

    Is there a solution to make inline-defined functions work with $.noConflict()?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    The problem isn't $.noConflict but because you have your function wrapped inside an anonymous function, what you need to do is move your welcome() function outside of the jQuery.ready() method so it becomes part of the global scope.

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2008
    Location
    Taiwan
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SgtLegend View Post
    The problem isn't $.noConflict but because you have your function wrapped inside an anonymous function, what you need to do is move your welcome() function outside of the jQuery.ready() method so it becomes part of the global scope.
    Thank you. I see.

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    No problem


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
  •