Saturday, 26 March 2016

Using Callback function while setting or getting contents and attributes ?


Callback function for text(), html() and val()

The callback function has two parameters :
   1. Index of the current element in the list of elements selected
   2. Original (old) value.
You can return the string to use as the new attribute value from the function.

Example 1.
$("#button1").click(function() {
  $("#test1").text( function(i,origText) {
    return "Old text: " + origText + 
           " New text: Hello Genius (index: " + i + ")";
  });
});

Example 2.
$("#button2").click(function() {
  $("#test2").html( function(i,origText) {
    return "Old html: " + origText + 
           " New html: Hello <b>Genius</b> (index: " + i + ")";
  });
});


Callback function for attr()

Example
$("button1").click(function() {
  $("#test").attr("href", function(i,origValue) {
    return origValue + "/genius";
  });
});

No comments:

Post a Comment

Note: only a member of this blog may post a comment.