There's a great tutorial on IBM's website which walked me through a simple search/results list using jQuery,PHP and Ajax.
I was able to make it work and it's really cool.
One problem. I want the results to be hyperlinks and I can't get any java script to run on the results.
Here is the script I have (includes what was in the tutorial plus the additional script necessary to ovverride the hyperlink, click behavior):
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
$("a").click(ClickInterceptor);
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
function ClickInterceptor(e)
{
window.alert("Hellow World!");
return false;
}
</script>
If i put the following html under the <body>
tag:
<a href="test">this will work</a>
That will display the alert window.
However, if I change the results to hyperlinks (found in find.php, listing 7 from the tutorial):
$string .= "<a href=\"test\">".$row->name."</a> - ";
It does not work.
Any idea on how to fix this?
The click
function binds when it is run. You need to change it to a live binding .
$("a").live("click", ClickInterceptor);
Or you can just bind it when you update the search results by putting the following after $("#search_results").html(data)
:
$("#search_results a").click(ClickInterceptor);
The problem is pretty simple actually, $("a").click(ClickInterceptor);
will only look for items that currently exist in the DOM. All you need to do is change that line to this:
$("a").live("click", ClickInterceptor);
I'd also advise taking the time to read more about jQuery's Events/live .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.