THIS IS NOT A DUPLICATE. THE SUGGESTED "DUPLICATE" IS IN REFERENCE TO OBJECTS THAT EXIST IN HTML, BUT HAVE NOT YET DRAWN IN THE DOM WHICH IS USUALLY REMEDIED USING THE ONLOAD EVENT. MY ISSUE IS SIMILAR, BUT THE CONTENT IS BEING CREATED -AFTER- THE PAGE HAS COMPLETELY RENDERED
The issue I am having is after replacing html, I can not register events on the newly formed html. The 'this' in the loop, doesn't seem to propegate with the new change, and there doesn't appear to be anyway to set it up.
What I would like it to do, is :
- Completely replace an html element (including itself as the parent, not just the inner content)
- Register events on the newly formed html during the replacement.
Following is a very basic demonstration of the problem.
HTML
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="MyNewSelect.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#SomeOldSelect').MyNewSelect();
});
</script>
</head>
<body>
<select id="SomeOldSelect">
<option value="foo">Bar</option>
</select>
</body>
</html>
jQuery function
(function( $ ) {
$.fn.MyNewSelect = function() {
this.each(function(){
// Rebuild the HTML from select tag
$(this).children('option').each(function(){
nHtml += '<span value="' + $(this).text() + '"><a class="fa" style="color: ' + $(this).val() + ';"></a>' + $(this).text() + '</span>';
});
nHtml += '<div id="' + $(this).attr("id") + '">' + nHtml + '</div>';
// Replace select tag with new html
$(this).replaceWith(nHtml);
// Register click event on new html
$(this).find('span').click(function() {
console.log($(this).text());
});
}
}
}( jQuery ));