jQuery, Uncaught TypeError
I have some javascript code on my webpage that is loading some divs onto the page. I also want to add onmouseenter, and onmouseleave ev开发者_StackOverflow社区ent handlers to each div. I am using jquery to add these handlers, but i get the error:
"Property '$' of object [object DOMWindow] is not a function"
My code looks like this, it is in a for loop:
var newItem = document.createElement('div');
newItem.innerHTML = results[i];
newItem.setAttribute("id", "resultDiv_" + i.toString());
dropDown.appendChild(newItem);
//Error on next line...
$("resultDiv_" + i.toString()).bind("mouseenter", function() {
$("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
});
Does anyone have any ideas why i am getting this error, or even what the error means?
Try replacing all occurrences of $
with jQuery
.
Also the selector $("resultDiv_" + i.toString())
won't likely return any elements. You probably meant: $("#resultDiv_" + i.toString())
And finally make sure this code is executed when the DOM is ready i.e. inside:
jQuery(function() {
// Put your code here
});
Are you sure that jQuery is properly loaded? Could it be a conflict with another javascript library?
(function ($) {
// All your code here
})(jQuery);
This fixed the problem for me.
What about trying this?
var newItem = document.createElement('div');
newItem.innerHTML = results[i];
newItem.setAttribute("id", "resultDiv_" + i.toString());
dropDown.appendChild(newItem);
//Error on next line...
$("resultDiv_" + i.toString()).mouseenter( function() {
$("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
});
Or make sure that $("resultDiv_" + i.toString())
is not null
. Use Firebug to inspect the element.
You might as well try this:
var newItem = jQuery('<div id="' + "resultDiv_" + i.toString() + '">+ results[i] + '</div');
jQuery(dropDown).append(newItem);
//Error on next line...
newItem.mouseenter(function(){
jQuery(this).css( 'background-color', 'blue');
});
or perhaps jQuery.noConflict will solve this.
精彩评论