因此,对于在线调查,我正在显示服务列表。我还希望我的用户能够搜索此列表。我编写了一个jQuery脚本,用于存储点击的服务以供日后使用。但是,当我搜索服务然后单击它时,jQuery脚本不响应。我不能,因为上帝的爱,弄清楚为什么它不起作用。
PHP
$sql = "SELECT ServiceAddress,ServiceID,ServiceIcon FROM Services WHERE ServiceName LIKE '%" . $_POST['data'] . "%'";
$query = mysql_query($sql);
$num_rows = mysql_num_rows($query);
if ($_POST['data'] == "") {
echo '<table></table>';
} else {
if ($num_rows > 0) {
echo '<ul>';
while($row = mysql_fetch_object($query)) {
echo '<li>
<a class="serviceIcon" id="serviceID' . $row->ServiceID . '">
<img id="' . $row->ServiceID . '" src="data:image/png;base64,' . base64_encode( $row->ServiceIcon ) . '" alt=\"\" height=\"80%\" /></a></li>';
};
echo '</ul>';
} else {
?>
<table>
<tr>
<td>Unfortunately, no results have been found. You can refine your search.</td>
</tr>
</table>
<?php
};
};
mysql_free_result($query);
exit();
的jQuery
$( "#searcher" ).keyup(function() {
var formData = {data: document.getElementById('searcher').value};
$.ajax({
type: "POST",
url: "Including/php/searcher.php",
data: formData,
success: function(data) {
document.getElementById('icons').innerHTML = data;
document.getElementById('icons').style.display = "block";
}
});
});
$('.serviceIcon').click(function(event) {
var id = $(this).attr('id');
$.variablesnamespace.selectedID = id.replace('serviceID', '');
});
答案 0 :(得分:1)
Click()不适用于动态添加的元素,请使用:
$('.serviceIcon').on('click', function(event) {
var id = $(this).attr('id');
$.variablesnamespace.selectedID = id.replace('serviceID', '');
});
答案 1 :(得分:0)
您需要委托或使用,因为您以编程方式将HTML添加到DOM。
$(function(){
$('.serviceIcon').on('click',function(event) {
var id = $(this).attr('id');
$.variablesnamespace.selectedID = id.replace('serviceID', '');
});
})