【问题标题】:Stopping the Jquery.map when a condition is met满足条件时停止 Jquery.map
【发布时间】:2013-08-12 06:37:20
【问题描述】:

我有以下代码:

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(", ");

上面的代码有助于查找唯一ID,一旦发现ID,它就会创建xpath。一旦地图功能到达检索ID并且地图功能应该停止的地步,我该如何停止地图功能?我试过 return false 和 break 但它不起作用。

还有其他建议吗?

【问题讨论】:

  • 只需使用.parentsUntil('[id]'),这样您就只有具有 id 属性的最接近父级的树。
  • 你能举个例子吗?如果合乎逻辑,人们可以投票给你的建议:)

标签: javascript jquery


【解决方案1】:

我认为不可能使用 .map(),你可能必须在这里使用 .each()

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(", ");

【讨论】:

  • 但如果我返回 false,它会显示:即:HTML,BODY,false,false,false,false,A
  • @madi 我忘了把 .map() 改成 .each()
  • Ohhhh....哈哈哈现在说得通了...我完全搞不懂有什么区别。哈哈哈....谢谢!
【解决方案2】:
   // 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(", ");

小提琴(更新):http://jsfiddle.net/SKqhc/5/

【讨论】:

  • 是的,这也很棒。它的作用与上述相同。太棒了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2016-04-12
  • 2020-01-11
  • 2022-06-17
  • 1970-01-01
  • 2019-01-29
  • 2013-11-22
相关资源
最近更新 更多