[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:

<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.

<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()?

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.

No problem