jQuery: use filter(), but work with both results

后端 未结 6 1837
孤城傲影
孤城傲影 2021-01-01 23:16

In jQuery, filter() reduces your result to those elements that fulfill a certain condition.

This splits the list in two parts. Working with the \"good

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 23:32

    $.fn.if = function(cond, ontrue, onfalse) {
      this.each(function() {
        if (cond.apply(this)) ontrue.apply(this);
        else onfalse.apply(this);
      });
    };
    
    $('some selector').if(function() {
      // determine result
    }, function() {
      // do something
    }, function() {
      // do something else
    });
    

    I'm not sure it is much more readable than putting an if inside an each manually, though.

提交回复
热议问题