Jquery css function undefined

jQuery span css throws undefined function error

The following tutorial shows you how to do «jQuery span css throws undefined function error».

The result is illustrated in the iframe.

You can check the full source code and open it in another tab using the links.

Javascript Source Code

The Javascript source code to do «jQuery span css throws undefined function error» is

var myInterval = null; var container = []; var i, j;// ww w .d e m o 2 s . co m var notrunning = true; var firstLetter, lastLetter; function callback1() < $("#palindromeRun").lettering(); $("#palindromeRun span").each(function (i, v) < container.push(v); >); i = 0; j = container.length-1; //console.log(container[j]); myInterval = setInterval(function() < if (i === j) < window.clearInterval(myInterval); container = []; > console.log(i+' : '+j+' : len:'+container.length); $(container[i]).css("color" : "red">); $(container[j]).css("color" : "red">); i++; j--; notrunning = true; >, 1000); > function pal (input) < var str = input.replace(/\s/g, ''); var str2 = str.replace(/\W/, ''); if (checkPal(str2, 0, str2.length-1)) < $("#textBox").css("color" : "green">); $("#response").html(input + " is a palindrome"); $("#palindromeRun").html(input); if (notrunning) < callback1(); notrunning = false; >> else < $("#textBox").css("color" : "red">); $("#response").html(input + " is not a palindrome"); > if (input.length "#response").html(""); $("#textBox").css("color" : "black">); > > function checkPal (input, i, j) < if (input.length return false; > if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) < return true; > else < if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) < return checkPal(input, ++i, --j); > else < return false; > > >
!-- w w w . d e m o 2 s . c o m --> http://jsbin.com Released under the MIT license: http://jsbin.mit-license.org --> script src="http://code.jquery.com/jquery-1.11.0.min.js">  script src="http://letteringjs.com/js/jquery.lettering-0.6.1.min.js">  p id="typing">  input type="text" id="textBox" onkeyup="pal(this.value);" value="" /> div id="response">  hr> div id="palindromeRun">  script> var myInterval = null; var container = []; var i, j; var notrunning = true; var firstLetter, lastLetter; function callback1() < $("#palindromeRun").lettering(); $("#palindromeRun span").each(function (i, v) < container.push(v); >); i = 0; j = container.length-1; //console.log(container[j]); myInterval = setInterval(function() < if (i === j) < window.clearInterval(myInterval); container = []; >console.log(i+' : '+j+' : len:'+container.length); $(container[i]).css("color" : "red">); $(container[j]).css("color" : "red">); i++; j--; notrunning = true; >, 1000); > function pal (input) < var str = input.replace(/\s/g, ''); var str2 = str.replace(/\W/, ''); if (checkPal(str2, 0, str2.length-1)) < $("#textBox").css("color" : "green">); $("#response").html(input + " is a palindrome"); $("#palindromeRun").html(input); if (notrunning) < callback1(); notrunning = false; >> else < $("#textBox").css("color" : "red">); $("#response").html(input + " is not a palindrome"); > if (input.length "#response").html(""); $("#textBox").css("color" : "black">); > > function checkPal (input, i, j) < if (input.length if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) < return true; >else < if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) < return checkPal(input, ++i, --j); > else < return false; >> > 

  • jQuery CSS Upon Window Resizing Breaks CSS
  • jQuery CSS with PHP DOM
  • jQuery cssRules with javascript is not permanent on client, getting wiped out after partial post back
  • jQuery span css throws undefined function error
  • jQuery visibility property in css
  • jQuery Charms bar using Metro UI CSS
  • jQuery Check for CSS calc doesn’t work in Chrome

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Почему jQuery возвращает undefined для функции css элемента?

jQuery 1.11.1, в Mac OS X Mavericks, последняя версия Safari. Я пытаюсь установить свойства CSS с помощью функции css. css() отсутствует в элементах. Во-первых, я проверил правильность выбора элемента:

// There is only one element that has var $container = $('#container'); // Selector returns a collection. I have to access first element: console.log($container[0]); // prints HTMLDivElement // css function is undefined console.log($container[0].css); // prints undefined // Also can't set any css value. Gives undefined error. $container[0].css(); 

Я удалил все с тестовой страницы. Он включает в себя jQuery, а в теле есть div с идентификатором. Очень простой. Ниже приведен код JavaScript, показанный выше. Любая идея, почему в div будет отсутствовать функция css?

Помните, что jQuery создает объект, который является надмножеством собственного объекта DOM. То есть он содержит все свойства/методы собственного объекта DOM плюс дополнительные свойства/методы, характерные для jQuery. — person War10ck &nbsp schedule 31.07.2014

Ответы (6)

Вы неправильно используете jQuery. Когда вы говорите $container[0] , вы получаете первый элемент DOM javascript объекта jQuery (к которому не привязаны какие-либо функции jquery). Если вы хотите получить цвет фона css элемента с помощью jQuery, вам нужно сделать $container.css(«background-color») и установить его $container.css(«background-color», «blue»); или $container.css(< "background-color": "blue" >);

[0] здесь дает вам объект DOM из объекта jQuery. Используйте jQuery, если вы хотите получить доступ к методу jQuery.

Поскольку функция css является методом объекта jquery. Когда вы делаете $container[0] , вы получаете первый узел DOM, соответствующий селектору, который не является объектом jquery. Попробуйте $container.css(. ) .

При доступе к элементам коллекции больше нет методов jQuery, только элементы DOM. Вы можете заменить:

Если у вас есть еще один элемент div с тем же атрибутом css, например, допустим, что приведенный ниже оператор возвращает более одного результата:

var $container = $('.container'); // Has 3 results 

И вы хотите получить определенный атрибут css элементов, тогда вы можете вернуть элемент dom в элемент jquery и сделать то, что хотите, как показано ниже:

Источник

Почему jQuery возвращает undefined для функции css элемента?

jQuery 1.11.1, на Mac OS X Mavericks, последняя версия Safari.

Я пытаюсь установить свойства CSS с помощью функции css. css() отсутствует в элементах.

Сначала я проверил, что элемент выбран правильно:

// There is only one element that has var $container = $('#container'); // Selector returns a collection. I have to access first element: console.log($container[0]); // prints HTMLDivElement // css function is undefined console.log($container[0].css); // prints undefined // Also can't set any css value. Gives undefined error. $container[0].css(); 

Ошибка TypeError: ‘undefined’ не является функцией (вычисляется ‘$container[0].css()’)

Я удалил все со страницы теста. Он включает в себя jQuery, а внутри тела есть div с идентификатором. Очень просто. Ниже приведен код JavaScript, показанный выше.

Есть идеи, почему в div не хватает функции css?

5 ответов

Вы используете JQuery неправильно. Когда ты сказал $container[0] Вы получаете первый элемент DOM javascript объекта jQuery (к которому не прикреплены никакие функции jquery). Если вы хотите получить цвет фона css элемента, используя jQuery, вам нужно сделать $container.css(«background-color») и установить его $container.css(«background-color», «blue»); или же $container.css(< "background-color": "blue" >);

Это потому, что вы выпадаете из объекта jQuery и используете элемент DOM.

[0] здесь вы получаете объект DOM из объекта jQuery.

Используйте jQuery, если вы хотите получить доступ к методу jQuery.

Поскольку css Функция — это метод объекта jquery. Когда вы делаете $container[0] Вы получаете первый узел DOM, который соответствует селектору, который не является объектом jquery.

Когда вы обращаетесь к элементам коллекции, у вас больше нет методов jQuery, только элементы DOM.

Если у вас есть еще один элемент div с тем же атрибутом css,

например, скажем, нижеприведенный оператор возвращает более одного результата:

var $container = $('.container'); // Has 3 results 

И вы хотите достичь определенных элементов атрибута css, тогда вы можете вернуть элемент dom в элемент jquery и сделать то, что хотите, как показано ниже:

Источник

Why Is jQuery Undefined?

Tom McFarlin

Tom McFarlin Last updated Jul 25, 2015

For the advanced JavaScript developers (and the advanced jQuery developers) among our readership, this article is not going to be of much help. Instead, we’re going to be focused on those who are just getting started with jQuery.

Perhaps you’ve gone through several JavaScript tutorials, built several small sites or projects that incorporate JavaScript into the page (or the site) to some degree, and now you’re ready to get started with a new framework or library.

If you’re reading this tutorial, then I assume you’re interested in getting started with jQuery. Or perhaps you’ve already started with jQuery but you’re encountering a couple of hurdles that are hindering your learning.

As frustrating as it can be to learn something new, hit a roadblock and then have to repeat it a little bit further down the line, the silver lining is that the chances are that your problems have been solved by someone else.

This isn’t necessarily true for more complex applications, but when you’re learning something new, you’re not the first person to bounce along the learning curve. To that end, you’re likely able to learn something from someone who has been there before.

And that’s exactly what we’re going to be covering in this tutorial. Specifically, we’re going to be talking about the problem when you receive the error message:

Uncaught ReferenceError: jQuery is undefined

Understanding the Problem

Before getting to the solution, let’s review exactly what’s happening. That is, in order to understand how we arrive at our solution, we need to understand the problem. Only then can we know how to solve what’s being displayed in the console.

Uncaught ReferenceError jQuery is not defined

If you’re familiar with JavaScript, then you know how confusing undefined can really be—that is, are we talking about the global object or a primitive value? That’s beyond the scope of this post (no pun intended!), but even if you’re not familiar with either definition, that doesn’t mean you’re not capable of diagnosing the problem.

Set Up a Sandbox

First, let’s go ahead and set up a page that includes the basics of what we need in order to work with the jQuery library to reproduce the error that we see above.

Start by creating the following HTML file and saving it somewhere on your local machine where you will be able to easily load it up in a web browser.

Источник

Читайте также:  Cpp project source code
Оцените статью