简体   繁体   English

jQuery,php和Ajax问题:无法使动态链接加载动态内容

[英]jQuery, php and Ajax issue: Can't make dynamic link load dynamic content

There's a great tutorial on IBM's website which walked me through a simple search/results list using jQuery,PHP and Ajax. IBM网站上有一个很棒的教程,它引导我使用jQuery,PHP和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. 我希望结果是超链接,并且我无法在结果上运行任何Java脚本。

Here is the script I have (includes what was in the tutorial plus the additional script necessary to ovverride the hyperlink, click behavior): 这是我拥有的脚本(包括本教程中的内容以及ovverride超链接,单击行为所必需的其他脚本):

<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: 如果我将以下html放在<body>标记下:

<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): 但是,如果我将结果更改为超链接(可在find.php中找到,本教程中的清单7 ):

$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. click功能在运行时绑定。 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").html(data)

$("#search_results a").click(ClickInterceptor);

The problem is pretty simple actually, $("a").click(ClickInterceptor); 这个问题实际上很简单, $("a").click(ClickInterceptor); will only look for items that currently exist in the DOM. 将仅查找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 . 我还建议您花些时间阅读有关jQuery的Events / live的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM