【问题标题】:Second execution follows href第二次执行遵循href
【发布时间】:2019-07-06 17:29:16
【问题描述】:

使用产品列表,一旦单击“从愿望清单中删除”按钮,它就会从所述产品列表中删除该产品,同时向后端发出 AJAX 请求,以便通过 SQL 将其删除。

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

我已经尝试从锚点 onclick="return removeFromWishlist();" 将其作为静态函数调用

还尝试通过 jQuery 事件而不是按钮标签本身在锚链接单击上执行 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。

【问题讨论】:

  • 尝试将jQuery('.button-wishlist').on('click', function (index)更改为jQuery(document).on('click', '.button-wishlist', function (event)
  • .on('eventName', cb) 回调的第一个参数是一个 jQuery event 对象 - 不是索引。 (由 imtheman 指出)
  • 永远不要使用.parent().parent().parent().parent().parent()....,只使用api.jquery.com/closest
  • 因为您在单击其中一个按钮时要删除并重新创建 HTML 按钮,所以新按钮没有注册相同的事件处理程序。 @imtheman 的解决方案应该可以工作,因为它将单个事件处理程序附加到文档中,以检查实际单击了哪个元素。
  • 太棒了@imtheman 非常感谢你!也感谢大家的回复,非常快速的回复:D

标签: javascript jquery


【解决方案1】:

在您的问题下关注我所有的 cmets...
我认为这就是您需要的所有代码。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2017-01-21
    相关资源
    最近更新 更多