没有调用Jquery函数

时间:2013-04-17 19:47:04

标签: php jquery

我有jquery函数从我的mysql数据库中调用php脚本的一些数据,jquery函数调用如下:

$(document).ready(function(){
  getTopFiveDeals();

当它运行时,它可以获得数据并构建一些HTML并将其插入到网页中。如下图所示:

   $('ul.special-list').append("<li><a href='#' class=restaurantItem  restaurant= '" + item.estName + "' adddress='" + item.estAddr + "'><img src= " + item.img_link + 
        " width='60' height='60' alt='" + item.estName + "'><div class='img-det'><strong class='title'> " + item.title + " </strong><p> " + item.desc_short +
        " <br>Expires: " + item.expiry_date + " </p><em class='price'>" + item.price + "</em></div></a><a href='dealDetail.html?id=" + item.id +
        "' class='det-link'>Detail</a>");

当我在下面有一个简单的jquery函数时,问题就开始了。该函数未被调用,而是页面重新加载到index.html#

$("a.restaurantItem").click(function (event) {
  alert('Hello');
}

非常感谢任何帮助和建议。

非常感谢

3 个答案:

答案 0 :(得分:6)

$("a.restaurantItem")被调用一次。它不寻找新的元素。您需要使用.on()的事件委派语法来匹配那些动态创建的元素:

$('ul.special-list').on('click', 'a.restaurantItem', function(e) {
    e.preventDefault();  // To stop the link from redirecting the browser
});

答案 1 :(得分:3)

您需要为动态元素委派事件处理程序,并阻止对锚点的默认操作(以避免滚动到顶部或跟随href)

$('ul.special-list').on('click', 'a.restaurantItem', function(event) {
    event.preventDefault();
    alert('Hello');
});

答案 2 :(得分:0)

以这种方式使用.on()

$(document).on('click',"a.restaurantItem",function (event){
    event.preventDefault();
    alert('Hello');
});
相关问题