I have a button that does not work in jquery. A button is passed from php to Jquery using json object. I have removed all other code just the button to test to try and solve this.
I create the same link and place it on my page in php. when the link is clicked a alert appears and works.
On the same page I have an additional button which is the same button, but this button has been returned from PHP via json to Jquery and
appended to the div. This link/button does not work? why is this? both appear the same!
Hope someone can advise as to what is happening here
Thanks
button returned from PHP
//Jquery basic test button for functionality (works if link button is already on HTML page)
$("[href='#test']").click(function() {
alert("has been clicked");
});
//JQuery extract of my code
var content;
$.each(data, function(i, item) {
content += item;
});
$(content).appendTo('#theframe');
},'json');
have also tried
$.each(data, function(i, item) {
content += item;
});
$('#theframe').html(content);
},'json');
//php returned
$json[] = '<a href="#test">View Post</a>';
echo json_encode($json);
//php button on page
<a href="#test">View Post</a>
Thanks
SOLVED with help from all posts, thank you! @Anthony’s example added the frame
$(‘#theframe’).on(‘click’, ‘[href=”#test”]’, function(e) {
alert(‘has been clicked’);
});
The
.click()function only adds the event handler to elements that exist when the code is run, so won’t affect any elements that are added dynamically later on. The easiest solution to get around this is to set up event delegation, using either the.on()(jQuery 1.7+) or.delegate()(prior to 1.7) functions. The.on()example would look like this: