Динамический список JQuery предотвращает многократное нажатие на один и тот же элемент - PullRequest
0 голосов
/ 25 июля 2011

Есть ли способ отключить кнопку после того, как она была нажата один раз, чтобы пользователь случайно не щелкнул элемент несколько раз?

У меня есть список jQuery, заполненный из массива JSON.Вот пример кода.Мне нужно добавить сюда функциональность, чтобы отключить обратный вызов клика после его щелчка один раз.

Если мой вопрос неясен, пожалуйста, сообщите мне, чтобы я мог отредактировать его с отсутствующим.

Спасибо!!

$('div[data-url*="details.page?productId"]').live("pageshow", function() {

var productId = getParameterByName("productId", $(this).data("url"));

$.mobile.pageLoading();

var product = catalog.products[productId];
$(this).find('#productName').text(product.name);
$(this).find('#productBrand').html(product.brand);
$(this).find('#productPrice').html(product.price);
$(this).find('#productDescription').html(product.description);
$(this).find('#productThumbnail').attr("src", product.thumbnail);
$(this).find('#add-to-cart').attr("product-item-id", productId);
$(this).find('#productSalePrice').html(product.salePrice);
$(this).find('#productSaleDesc').html(product.sale_desc);
$(this).find('#productCategory').html(product.category);
$(this).find('#longDescription').html(product.longDesc);

for (k = 1; k <= parseInt(product.rating); k++) {
    var starId = "#star" + k;
    $(this).find(starId).attr('src', '/pub/3/resources/ti/store/mobile/star-fill_30x25.png')
}

if (product.salePrice == '') {
    $(this).find('#productPrice').css('text-decoration', 'none')

}

else if (product.price > product.salePrice) {
    $(this).find('#productPrice').css('text-decoration', 'line-through');
    $(this).find('#salePrice').html(product.salePrice);
    $(this).find('#saleDesc').html(product.sale_desc);

}

$.mobile.pageLoading(true);


});


function refreshList() {
console.debug('About to refresh with sort type : ' + sortType);

switch (sortType) {
    case 'sort-a-z':
        catalog.products.sort(sort_by('name', false));
        break;
    case 'sort-z-a':
        catalog.products.sort(sort_by('name', true));
        break;
    case 'sort-price-up':
        catalog.products.sort(sort_by('price', false, parseFloat));
        break;
    case 'sort-price-down':
        catalog.products.sort(sort_by('price', true, parseFloat));
        break;
    default :

}

var items = [];


$.each(catalog.products,
      function(index, value) {

          if (
                  ((!filterValue ) || value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
                          && ((!brand) || value.brand.toUpperCase().indexOf(brand.toUpperCase()) != -1)
                          && ((!category) || value.category.toUpperCase().indexOf(category.toUpperCase()) != -1)
                          && ((!sport) || value.sport.toUpperCase().indexOf(sport.toUpperCase()) != -1)
                  ) {

              var priceInfo;
              if(value.salePrice === '') {
                  priceInfo = '<h4 style="margin-top:3px;margin-bottom:0px;color:#75a8db "> $' + value.price + '</h4></a></li>';
              } else {
                  priceInfo = '<h4 style="margin-top:3px;margin-bottom:0px; "><span style="text-decoration: line-through;font-size:small;">$' + value.price +
                          '</span><span style="color:#75a8db;"> $' + value.salePrice + '</span></h4></a></li>';
              }

              items.push('<li id="' + index + '">' +
                      '<a data-identity="productId"  href="./details.page?productId=' + index + '" >' +
                      '<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
                      '<p style="margin-bottom:0px;margin-top:0px;">' + value.brand + '</p>' +
                      '<h3 style="margin-top:0px;margin-bottom:0px;">' + value.name + '</h3>' +
                      priceInfo);



      }}
        );

if (items.length === 0) {
    items.push('<p style="text-align: left;margin-left: 10px">No results found.</p>');
}
productListView.html(items.join(''));
productListView.listview('refresh');


}

Ответы [ 3 ]

1 голос
/ 25 июля 2011

Вы, вероятно, связываете обработчики кликов, используя .click(...), верно?
Если это так, просто используйте .one('click', ...).

0 голосов
/ 25 июля 2011

Вы можете связать, используя метод "one" вместо связывания (и при необходимости подключать его снова и снова).

Но более гибкий шаблон - связать что-либо (скажем, имя класса), удалить это имя класса иподключите его при необходимости - это работает с жизненными событиями.

$("div.clickme").live("click", function() {
   $(this).removeClass("clickme")
   ...
   $(this).addClass("clickme")
})

Вы также можете комбинировать эту технику с использованием setTimeout или чего-то еще.

0 голосов
/ 25 июля 2011

Это должно быть все, что вам нужно

$(li).click(function(){
  $(this).unbind('click'); 
  //do whatever you want here
});

РЕДАКТИРОВАТЬ: Если вы хотите удалить ссылку при нажатии, просто сделайте это

$('.item a').one('click',function(){
  $(this).attr('href','javascript:void(0)');
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...