开发者

jQuery Sanity Check

开发者 https://www.devze.com 2022-12-19 16:25 出处:网络
This is driving me crazy. Please someone tell me I\'m not crazy: var constraints = $(\'.traffic-constraints :开发者_开发知识库input\');

This is driving me crazy. Please someone tell me I'm not crazy:

var constraints = $('.traffic-constraints :开发者_开发知识库input');
console.log(constraints);

var i;
for (i = 0; i < constraints.length; i++) {
  if (constraints[i].val() > 0) { //<-------- errorrzz
....

the console tells me that i do, in fact, have input objects in my selector (5 of them). however, i get the following error: constraints[i].val is not a function

wtf?


First, use .each() it's easier :)

But, to answer the question why doesn't it work...you're dealing with a dom element with that index, you need to wrap it or .eq(i) acesss it:

for (i = 0; i < constraints.length; i++) {
  if ($(constraints[i]).val() > 0) {

Or (better, but still use .each()!):

for (i = 0; i < constraints.length; i++) {
  if (constraints.eq(i).val() > 0) {


Accessing elements like that (e.g. $('.traffic-constraints :input')[0]) returns the HTML element (or DOM node, to be more pedantic). If you want to get the element jQuery-wrapped, call constraints.eq (i)


jQuery has an .each() method to loop through the elements of a collection. You can use it as such:

$('.traffic-constraints :input').each(function(index) {
    if($(this).val() > 0) {
       doSomething();
    }
});

The reason why your loop isn't working is that the elements are not extended with jQuery's methods. The following fixes it:

var constraints = $('.traffic-constraints :input');
console.log(constraints);

var i;
for (i = 0; i < constraints.length; i++) {
    if ($(constraints[i]).val() > 0) {
        doSomething();
    }
}

But for reasons of code maintainability and best practices, use .each(). It isn't noticeably slower and is easier to maintain and understand.


Why don't you use each?

0

精彩评论

暂无评论...
验证码 换一张
取 消