0

I am working on jQuery Mobile.

I have a view in which I am displaying the collabsible list which is being loaded dynamically. Hence my jQuery file gets the JSON data, runs the loop around $('mylist').append(..data for each row..).

Now in every collapsible item, I am adding a button which has to run a JavaScript function alongwith the parameters. This is where I am stucked. Somehow the event is not fired on click. Is it because of the fact that no event is generated or the the parameters I am passing in variables are the main problem.

$('#main')
  .bind("pageshow", function (event) { 
    var cusid = getUrlVars()["cusid"]; 
    var locid = getUrlVars()["locid"]; 
    $.getJSON("localhost/mserv/Offers.php";, function(data) { 
      $.each(data, function(index, offer){ 
        $('#cat_list').append("<div align='center' data-role='collapsible'><h3>offer.name</h3><p>offer.price</p><input type= 'button' onclick='addItem("+offer.id+",'"+offer.name+"',"+offer.price+")' value='Add To Cart'></div>"); 
      }); 
    $('#cat_list').collapsibleset('refresh'); 
  });
4

1 回答 1

0

我想我知道可能是什么问题,尽管实际上您没有提供足够的信息(尤其是您使用的代码):

jQuery mobile 总是通过 AJAX 向 DOM 添加元素。如果你想为通过 AJAX 添加到 DOM 的元素添加事件监听器,那么你需要使用on()而不是click(),例如。

所以更换

$('clickableElement').click(function() {
    ...
});

$('clickableElement').on('click', function() {
    ...
});

通过这种方式,您将 click-eventlistener 绑定到您的元素,即使它在最初加载 DOM 时(第一次调用您的页面)不存在,只要它通过 AJAX 添加到 DOM。

于 2012-05-02T21:20:21.973 回答