Home > database >  Filter function - calling function on returned element?
Filter function - calling function on returned element?

Time:11-18

I have a predefined set of elements on a page. I initially retrieve them via

scrollItems = $('div.topicrow-header')

At times I perform operations on this set. I use the filter method like so

scrollItems.filter('#'   curTopicId).addClass("stick");

I am fairly new to jQuery and Javascript, at times not really sure what the 'correct' way is to do certain things, and so I try and work my way through it. In this case, in addition to calling addClass on the element returned by filter, I want to perform other operations, like add a variable to the matched element, so that I have available, say, scrollItems[idx].startTime

How would I alter the above, so that in principle, I can syntactically do

scrollItems.filter('#'   curTopicId).doStuff( function {
   addClass("stick");
   scrollItems[matched_index].somevar = someval;
})

Would I just do something like

matched = scrollItems.filter('#'   curTopicId);
if (matched.length() != 0 ) {
   matched.addClass("stick");
   idx = matched.index();
   matched[idx].somevar = someval;
}

Edit:

I ended up doing the following, and seems to work. Still curious if there is a more 'pro' way...

$.each(scrollItems, function( index, value ) {
    if (value.id === curTopicId) {
       $(value).addClass("stick");
       topic_times[index].startTime = Date.now() / 1000 | 0;
       cur_idx = index;
       return false;
    }
});

CodePudding user response:

You could define a function that will retrieve a "scrollItem" from its id, add a class and an attribute to this item :

function doStuff(id){
    let elem = $('div.topicrow-header').filter("#"   id);
    elem.addClass("stick");
    elem.prop("startTime", Date.now() / 1000 | 0);
}

And then call this function for your current topic id :

doStuff(curTopicId);

CodePudding user response:

In my eyes you went into same pitfall like me, when I faced to filter() at jQuery.

https://api.jquery.com/filter/ is the documentaion for this function. I spent at least two hours to understand this page. So what is your mistake, in my eyes?

The most important thing of filter() function is, it needs an handwritten business logic. This is in charge for "filtering" the items from passed list. The bussines logic expects an matched item to return it.

let scrollItems = $('div.topicrow-header');
let itemsListAftering = $(scrollItems).filter(
 if ($(this) put here your condition)
 {
   return $(this);
 } 
);

After that your new workingbase is itemsListAftering:

$(itemsListAftering).each(function(){
  $(this).addClass("stick");
  $(this).prop("startTime", Date.now() / 1000 | 0);
});

Maybe the syntax of second part is not correct, so feel free to correct it.

  • Related