Process the node selected by J-query as a map

Asked 2 years ago, Updated 2 years ago, 42 views

You are writing a code to check the values of some input tags. Using jquery selector to reduce code as much as possible.

$('form[name="an"] .cell input').map(function(eachNode){
    if(!eachNode.value){
        console.log ('no value');
    }else{
        console.log ('value present');
    }
});

When you enter $('form[name="an"].cell input') from the console, you will see an object with a length of 3 and each pointing to an input node. If you use the above code, you will end with 'no value' once regardless of the input value.

I turned console.log(eachNode) to see how the inside of the map works, but only 0, 1, and 2 came out. Do I still misunderstand the map?

jquery javascript

2022-09-21 21:09

1 Answers

According to API document , the function corresponding to callback in map(callback) should be in the form of Function(Integrator index, Element)=>Object.

In other words, in the example of the question, the index is thought of in eachNode, and if you want direct access to dom, you need to use a double re-factor.

To access individually corresponding items in the map function, you can use one of the following two methods.

$('form[name="an"] .cell input').map(function() {
    var node = $(this);
    if(!$node.val()) {
      console.log ('no value');
    } } else {
      console.log ('value present');
    }
});

Use the domain directly

$('form[name="an"] .cell input').map(function(index,el) {
    if(!el.value) {
      console.log ('no value');
    } } else {
      console.log ('value present');
    }
});


2022-09-21 21:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.