简体   繁体   中英

Stopping the Jquery.map when a condition is met

I have the following code:

var parentEls = node.parents() 
    .map(function () {

        var curParentID = this.getAttribute("id"); 
        var curParentClass = this.getAttribute("class");

        if(curParentID) {
            return this.tagName + "#" + curParentID;
            /*stop the map function from proceeding*/
        } else {
            return this.tagName;
        }
    })
    .get().reverse().join(", ");

The above code helps to find search for unique id and once an ID is spotted , it creates the xpath. How can i stop the the map function once it has come to a point where the id is retrieved and the map function should stop? I tried return false and break but it does not work.

Is there any other suggestion?

I don't think it is possible using .map(), you may have to use .each() here

var temp = [];
node.parents().each(function () {
    var curParentID = this.getAttribute("id"); 
    var curParentClass = this.getAttribute("class"); 
    if(curParentID){
        temp.push(this.tagName + "#" + curParentID);
        return false;
    } else {
        temp.push(this.tagName);
    }
});
var parentEls = temp.reverse().join(", ");
   // parentsUntil() doesn't include the element specified by selector, 
   // so you need to add the closest ancestor with id attribute to the collection
   var parentEls = node.parentsUntil('[id]').add( node.closest('[id]') )
        .map(function () {
            return this.id ? '#' + this.id : this.tagName;
        })
        .get().join(", ");

Fiddle (updated): http://jsfiddle.net/SKqhc/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM