javascript - 第二次执行遵循 href

标签 javascript jquery

有了产品列表,一旦单击“从心愿单中删除”按钮,它就会从所述产品列表中删除该产品,并向后端发送 AJAX 请求以通过 SQL 将其删除。

第一次点击有效,jQuery 执行,然后产品被删除。第二次单击任何产品的相同类型的按钮,然后加载 href 而不是执行 jQuery,这意味着执行 jQuery。

我试过从 anchor onclick="return removeFromWishlist();"将其作为静态函数调用

还尝试通过 jQuery 事件而不是按钮标记本身在 anchor 链接单击上执行 jQuery。

jQuery('.button-wishlist').on('click', function (index) {

    event.preventDefault();

    // Calls the AJAX to remove it from the back-end via SQL etc
    // The response is JSON within the following call
    removeProductAjax(this);

    console.log('removing product from the wishlist');

    // Get the cell position of the product to remove from the wishlist
    var position = jQuery(this).parent().parent().parent().data('cell');

    var html = [];
    var cells = 0;

    jQuery('.wishlist_container .col-md-4').each (function () {
        //
        if (jQuery(this).data('cell') == position) {
            cells++;
        }
        else if (jQuery(this).data('cell') !== undefined) {
            html.push(jQuery(this).html());
            cells++;
        }
    });

    var upto = 0;

    jQuery('.product-row').each (function () {
        var self = this;
        // Repopulate all the product lists excluding the one removed
        jQuery(self).children().each (function () {
            jQuery(this).html(html[upto]);
            upto++;
        });
    });

    // Then clear everything from upto and onwards!
    console.log('cells: ' + cells);
    console.log('upto: ' + upto);

    // let's change from array to 'standard' counting
    upto--;

    // Remove the last element!
    jQuery('.product-row').find('[data-cell=' + upto + ']').remove();

    // Check for any empty rows
    jQuery('.product-row').each (function () {
        if (jQuery(this).children().length == 0) {
            jQuery(this).remove();
        }
    });
});

HTML 基本上是:

<div class="row product-row">
    <div class="row product-row"><div class="col-md-4" data-cell="0">
        <h1>product 1</h1>
        <a href="./page.php?page=cart&amp;unwish=660986" data-index="660986" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
            <button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
        </a>
    </div>
    <div class="col-md-4" data-cell="1">
        <h1>product 2</h1>
        <a href="./page.php?page=cart&amp;unwish=661086" data-index="661086" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
            <button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
        </a>
    </div>
    <div class="col-md-4" data-cell="2">
        <h1>product 3</h1>
        <a href="./page.php?page=cart&amp;unwish=661067" data-index="661067" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
            <button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
        </a>
    </div>
</div>

我希望它在每次单击“从心愿单中删除”按钮时执行 jQuery,无论是什么产品,无论是什么顺序。因此,您可以使用 AJAX/jQuery 一个接一个地取消许多产品。

最佳答案

在你的问题下关注我的所有评论......
我认为这就是您需要的全部代码。

PHP(我使用的是:../removeProduct.php?id=)应该用一些 JSON 来响应,比如:

// PHP does here some DB deletions or fails.
// Send back to AJAX the deleted item ID (or null)
// and some (error?) message
echo json_encode(['id' => $id, 'message' => $message]);
exit;
// No more PHP here. We exit.
// jQuery will collect that JSON response as `res`

jQuery(function($) {

  function removeProductAjax(id) {
    $.get("../removeProduct.php?id=" + id, 'json').always(function(res) {
    
      if (res.statusText === 'error') { // General error (path invalid or something...)
        return alert(`Error: Cannot remove product ID: ${id}`); // and exit function
      }
      
      if (!res.id) { // Something happened
        return alert(res.message); // Alert PHP's error message and exit function.
      }
      
      // All OK. Remove item from products
      $(".product-row").find(`[data-id="${res.id}"]`).remove();
    });
  }

  $('.product-row').on('click', '.product-remove', function(ev) {
    ev.preventDefault();
    removeProductAjax($(this).data('id'));
  });

});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<div class="row product-row">
  <div class="col-md-4" data-id="660986">
    <h3>product 1</h3>
    <button type="button" class="btn product-remove" data-id="660986">Remove from Wishlist</button>
  </div>
  <div class="col-md-4" data-id="661086">
    <h3>product 2</h3>
    <button type="button" class="btn product-remove" data-id="661086">Remove from Wishlist</button>
  </div>
  <div class="col-md-4" data-id="661067">
    <h3>product 3</h3>
    <button type="button" class="btn product-remove" data-id="661067">Remove from Wishlist</button>
  </div>
</div>

<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

关于javascript - 第二次执行遵循 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54660735/

相关文章:

jquery - PhoneGap 版本 : SocialSharing Plugin Not Loading

jquery - Knockout JS、TextArea 在数据绑定(bind)到 attr ID 时添加值

javascript - 使用 JavaScript 构建猜数游戏程序

javascript - jquery removeAttr ('class' ) 仍然保留类的元素

javascript - 如何避免 redux 中的 immutation

javascript - 多个元素的包装函数 Jquery

javascript - 设置下拉列表的选定值,其中使用 Jquery 动态附加下拉列表的选项

javascript - 一个网站与另一个网站的内容交替

javascript - 如何在 TIVO 设备上启动 asp.net 网站?

jquery - 如何检查输入文件是否为空,如果使用 jquery 选择了 png 格式,还显示警告