JQuery Replace Javascript Function Return Value

OK I'm just starting with jQuery.

I have a page with a table of date values. Each of them is wrapped with a tag that I can find with $ ('MyTag'). <mytag>2009-10-31</mytag>

How, using jQuery, will I

  • take each of the source code values ​​and
  • pass it to javascript function
  • then replace this original value in the table with the result of the function calculation.

So, <mytag>2009-10-31</mytag> will be replaced by <mytag>Very Late</mytag>

I have a Javascript function. My question is jQuery syntax for passing a single value.

+4
source share
4 answers

First, you will need an element selector like

 $('table') 

Will select all <table> elements in your html. Thus,

 $('mytag') 

will provide you with your items. You will get a jQuery object (not a DOM object). See http://docs.jquery.com/Selectors

Then you want to call a function for each of your elements. To do this, we call the .each function and pass the function to call for each element:

 $('mytag').each(function(){ //function code goes here }); 

(see http://docs.jquery.com/Utilities/jQuery.each )

The function in this case is called the Anonymous>

Then you want to reference the current object in iteration, so we use the DOM this element and transfer it to the jquery object. To get the value, we use the .text () function ( http://docs.jquery.com/Attributes/text )

 $('mytag').each(function(){ $(this).text() }); 

Note: if it were an input element, you would use .val ()

Passing it to a function is simple:

  ... MyFunction($(this).text()); ... 

The text () function has an overloaded implementation that allows you to set text if you pass in a value:

  $(this).text(someval); 

So we can do it in our code

  ... $(this).text(MyFunction($(this).text())); ... 

Creating our final code:

 $('mytag').each(function(){ $(this).text(MyFunction($(this).text())); }); 
+6
source
 $('mytag').each(function (index,tag) { $(tag).text( myFunc($(tag).text()) ); }); 
0
source
 $("mytag").each(function() { $(this).html("Very Late"); }); 
0
source
 $('mytag').each(function() { $(this).text(someFunction($(this).text())); }); 

But, due to the sound of your problem, you might be better served by the jQuery-timeago plugin . For your specific case, you might want to resolve dates in the future:

 jQuery.timeago.settings.allowFuture = true; 

... and you will want to create your own language. See examples of language overrides . You can define several "late" and "very late" values. You can also pass a function to each of them to change the value depending on how many days ago there was a timestamp.

0
source

All Articles