How to make this jquery function reusable?
Hai this is my jquery function,
function getRecordspage(curPage, pagSize) {
开发者_StackOverflow $.ajax({
type: "POST",
url: "Default.aspx/GetRecords",
data: "{'currentPage':" + curPage + ",'pagesize':" + pagSize + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
var strarr = jsonObj.d.split('##');
var jsob = jQuery.parseJSON(strarr[0]);
$.each(jsob.Table, function(i, employee) {
$('<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category :</span> <span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis :</span> <span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary :</span> <span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address :</span> <span class="resultfieldvalues">' + employee.Address + '</span></div>').appendTo('#ResultsDiv');
});
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
}
});
}
In my page i have this jquery script,
$("#lnkbtn0").click(function() {
getRecordspage(1, 5)
});
And my page has
<a ID="lnkbtn0" class="page-numbers">1</a>
<a ID="lnkbtn1" class="page-numbers">2</a>
<a ID="lnkbtn2" class="page-numbers">3</a>
<a ID="lnkbtn3" class="page-numbers">4</a>
How to make other link buttons to call this function with diff curPage
parameter...
I think you mean you want to apply the text of links with ID starting with linkbtn as the first parameter:
$("a[id^=linkbtn]").click(function() {
getRecordspage($(this).text(), 5);
return false;
});
See http://api.jquery.com/attribute-starts-with-selector/
Alternatively, you could just use a class selector:
$("a.page-numbers").click(function() {
getRecordspage($(this).text(), 5);
return false;
});
If you don't mind using Plain old javascript
<a ID="lnkbtn0" class="page-numbers" href="#" onclick="getRecordsPage(1,5)">1</a>
<a ID="lnkbtn1" class="page-numbers" href="#" onclick="getRecordsPage(2,5)">2</a>
<a ID="lnkbtn2" class="page-numbers" href="#" onclick="getRecordsPage(3,5)">3</a>
<a ID="lnkbtn3" class="page-numbers" href="#" onclick="getRecordsPage(4,5)">4</a>
Make sure you preventDefault
on the <a>
tags.
Else, if you really want to go JQuery.
$("a[id^=linkbtn]").each(function() {
$(this).click(function() {
getRecordspage($(this).text(), 5);
});
});
UPDATE Use class selectors (as karim79) suggested.
精彩评论