谁能帮我解决问题?如何使 ajax 提供的链接正常工作?
我尝试将一些链接直接写入文档,它们运行良好,但"导入"的链接却没有。
JSFiddle
-> res/ajax/search.php
<?php
$search = $_POST['search'];
if( $search != "" ) {
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('invoice');
$query = "SELECT * FROM profile";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for( $a=1; $a <= $rows; $a++ ) {
$query = "SELECT * FROM profile WHERE full_name LIKE '%$search%' AND id='$a'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
if($array != "") {
echo "<a href='#' class='address'>" . $array['full_name'] . "</a><br />";
}
}
}
echo "<a href='#' class='address'>currywurst</a><br />";
echo "<a href='#' class='address'>bratwurst</a><br />";
?>
使用:
$(document).on('click', '.address', function(){
alert('something');
});
而不是:
$('.address').click(function(){
alert('something');
});
您应该尝试将处理程序绑定到 ajax 回调中的 ajax 加载内容。试试这个:
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
$.post('res/ajax/search.php',
{
search: $('input[name="search"]').val()
},
function(data) {
$('#search-preview').html(data);
// onclick moved to ajax callback function
$('.address').click(function(){
alert('something');
});
});
});
});