click wont work when placed with jquery .html() or .replace()
Hi im trying to replace a link if i click this other link. but i cant get click to work when i add the link with jquery replace()
or html();
. what im i doing wrong?
this is the code i try to use
$(document).ready(function() {
var countTotal = $('#myTable tr').length;
$("#hideTotalCount").val(countTotal);
$('#clickMeAll').click(function() {
var开发者_运维问答 totalCount = $("#hideTotalCount").val() - 1;
$('#myTable').paginateTable({ rowsPerPage: totalCount, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').replaceWith("<a href='#' id='clickMeRegular'>Back to regular</a>");
});
$('#clickMeRegular').click(function() {
var totalCount = $("#original").val();
$('#myTable').paginateTable({ rowsPerPage: totalCount, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').replaceWith("<a href='#' id='clickMeAll'>ViewAll</a>");
});
$('#myTable').paginateTable({ rowsPerPage: 5, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').html("<a href='#' id='clickMeAll'>ViewAll</a>");
});
and #placeLink
is just a regular <span>
maybe somebody know something that can push me in the right direction? thanks
The problem that the replacement DOM node has no click event attached. When you call $("#clickMeAll").click(...), jQuery searches for an element with id clickMeAll that is present right now and assigns an event to it.
If you replace it with some other html code later on, the event is not automatically re-assigned to the new DOM node.
Two solutions:
- Use jQuery live events
- Do not replace but just hide / show #clickMeAll and #clickMeRegular. They both exist all the time, but only one of them is visible. (better solution).
Consider using jQuery live.
$(document).ready(function() {
var countTotal = $('#myTable tr').length;
$("#hideTotalCount").val(countTotal);
$('body').delegate('#clickMeAll', 'click' ,function() {
var totalCount = $("#hideTotalCount").val() - 1;
$('#myTable').paginateTable({ rowsPerPage: totalCount, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').replaceWith("<a href='#' id='clickMeRegular'>Back to regular</a>");
});
$('body').delegate('#clickMeRegular', 'click' ,function() {
var totalCount = $("#original").val();
$('#myTable').paginateTable({ rowsPerPage: totalCount, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').replaceWith("<a href='#' id='clickMeAll'>ViewAll</a>");
});
$('#myTable').paginateTable({ rowsPerPage: 5, pager: '.pageNumbersOnly', maxPageNumbers: 4 });
$('#placeLink').html("<a href='#' id='clickMeAll'>ViewAll</a>");
});
will work correctly I hope
精彩评论