【问题标题】:jQuery preventDefault doesn't always workjQuery preventDefault 并不总是有效
【发布时间】:2014-11-13 10:01:55
【问题描述】:

我有一个名为 showBasket 的函数,它向您显示添加到 shoppingBasket 的项目列表。每次用户单击链接时都会发生这种情况;每次您在菜单外单击时,它都会再次隐藏起来。

我的问题是,在这个菜单中,我有一个与每个项目相关的链接列表,允许您删除所选项目。此链接有时可以正常工作,并且根据我使用的网络浏览器也可以正常工作。

我想要的是在不刷新所有网页的情况下删除该项目,所以我认为我必须对链接做一个preventDefault,而且当我调试我的代码时,我看到它重复了很多次,所以出了点问题,特别是当我发现有时我没有得到我想要的结果时。

如您所见,我使用了两个 ajax 函数,一个用于删除我认为可以正常工作的项目,另一个用于刷新数据。

如果有人可以帮助我,那就太好了。我被这个困住了。

/*
SHOWS AND HIDE A BASKET MENU, EVERYTIME YOU CLICK IN THE SELECTED LINK
THIS MENU SHOWS A LIST OF ARTICLES ADDED TO A SHOPPING BASKET, AND EACH ITEM OF THE LIST
HAS A LINK THAT ALLOWS YOU TO DELETE THE SELECTED ITEM.

*/

function showBasket(){
    var $basket=$('#basket');
    var nstyle=$basket.css("display");
    $basket.on('click','a[title="delete article"]',function(e){
    e.preventDefault();
        del($(this));
        updateBasket($(this));

        function del(m){
            var n=m.attr("href");
            n=n.split("=");
            var l=n[1];
            $.ajax({
                type:"GET",
                data:{productoRemoveId:l},
            });
            return false;
        }

        function updateBasket(m){
            $.ajax({
                url:'updateBasket.php',
                success: function(response){
                    $cesta.html(response);
                }
            });
            return false;
        }
        return false;
    });
    if (nstyle=='none'){
        $basket.fadeIn(false,function(){//showing the basket
            $('html').bind("click",function(){
                $basket.fadeOut();//hidding the basket
                $("html").unbind("click");
            });
        });
    }
}

这是 HTML 代码,相对于上面的脚本:

<div id="basket" class="box_menu" style="display: table;">  <div class="row header">
    <h1>Mi cesta</h1>
        <span>3 articulos añadidos)</span>  
</div>
    <div class="detalle">
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>lechuga</span></div>
            <div class="celda_detalle"><span>9.25</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=5">Eliminar Articulo</a></div>
        </div>
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>Lejia</span></div>
            <div class="celda_detalle"><span>8.23</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=2">Eliminar Articulo</a></div>
        </div>
        <div class="row">
            <div class="celda_detalle"><input type="text" name="tecantidad" maxlength="3" value="1"></div>
            <div class="celda_detalle"><span>limones</span></div>
            <div class="celda_detalle"><span>8.25</span></div>
            <div class="celda_detalle"><a title="delete article" href="./bienvenida.php?productoRemove=3">Eliminar Articulo</a></div>
        </div>
    </div>
        <div class="fila pie">
            <div class="celda_pie">
                <span>Subtotal: 25.73€</span>
            </div>
            <div class="celda_pie">
                <a title="Save Shopping" href="#">Save Shopping</a>
            </div>
            <div class="celda_pie">
                <a title="Pay Shopping" href="#">Pay Shopping</a>
            </div>
</div></div>

我已尝试将主要代码翻译成英文,所以如果您发现任何错误,请告诉我。

PHP 代码我不会全部发布,但我会发布最相关的一个:

类 ShoppingCart 实现 Iterator、Countable {

// Array stores the list of items in the cart:
protected $items = array();

// For tracking iterations:
protected $position = 0;

// For storing the IDs, as a convenience:
protected $ids = array();

private $subtotal  = 0;
private $itemCount = 0;

//MORE CODE ....
// Removes an item from the cart:
public function deleteItem($id) {

    // Need the unique item id:
        //$id = $item->getId();

    // Remove it:
    if (isset($this->items[$id])) {
        unset($this->items[$id]);

        // Remove the stored id, too:
        $index = array_search($id, $this->ids);
        unset($this->ids[$index]);

        // Recreate that array to prevent holes:
        $this->ids = array_values($this->ids);

    }

    $this->itemCount=$this->count();

    $this->subtotal=$this->calcularTotal();
    return true;

} // End of deleteItem() method.

public function display_cart() {
    ////////////////////////////////////////////////////////////////////////
    // Output the cart

    // Return specified number of tabs to improve readability of HTML output
    function tab($n) {
        $tabs = null;
        while ($n > 0) {
            $tabs .= "\t";
            --$n;
        }
        return $tabs;
    }

    if (isset($_GET['productoRemove']))
        if($_GET['productoRemove'] && !$_POST) {
            $idp=$_GET['productoRemove'];
            $this->deleteItem($idp);
        }


    // Display the cart header
    echo tab(1) . "<div class='row header'>\n";
    echo tab(1) . "<h1>Mi cesta</h1>\n";
    echo tab(2) . "<span>". $this->count()." articles added)</span>";
    echo tab(1) . "</div>\n";
    echo tab(1) . "<div class='detalle'>";
    if ($this->count()==0){
        echo tab(2) . "<div class='row'>";
        echo tab(3) . "<span style='display:table-cell; width:450px; vertical-align:middle; text-align:center; color:#666; font-style:italic; font-size:12px;'>La cesta está vacía</span>";
        echo tab(2) . "</div>\n";
    } else {
        //$producto=$this->current();
        $lista=$this->getItems();
        foreach ($lista as $producto){
            echo tab(2) . "<div class='fila' class=".$producto['item']->getId().">\n";
            echo tab(3) . "<div class='celda_detalle'><input type='text' name='tecantidad' maxlength='3' value='".$producto['qty']."'></div>";
            echo tab(3) . "<div class='celda_detalle'><span>".$producto['item']->getNombre()."</span></div>";
            echo tab(3) . "<div class='celda_detalle'><span>".$producto['item']->getPrecio()."</span></div>";
            echo tab(3) . "<div class='celda_detalle'><a title='delete article' href='./bienvenida.php?productoRemove=".$producto['item']->getId()."'>Eliminar Articulo</a></div>";
            echo tab(2) . "</div>\n";
        }
    }
    echo tab(1) . "</div>\n";
    echo tab(2) . "<div class='fila pie'>";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<span>Subtotal: ".$this->calcularTotal()."€</span>";
    echo tab(3) . "</div>\n";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<a title='Save Shopping' href='#'>Save Shopping</a>";
    echo tab(3) . "</div>\n";
    echo tab(3) . "<div class='celda_pie'>";
    echo tab(4) . "<a title='Finish Shopping' href='#'>Finish Shopping</a>";
    echo tab(3) . "</div>\n";
}
}
// Start a new session in case it hasn't already been started on the including page
@session_start();

// Initialize jcart after session start
if (empty($_SESSION['carrito']))
    $carrito="";
else
    $carrito = $_SESSION['carrito'];
if(!is_object($carrito)) {
    $carrito = $_SESSION['carrito'] = new ShoppingCart();
}

为了更好地了解我得到了什么,我还展示了一张图片:

我的代码灵感来自以下代码:

http://conceptlogic.com/jcart/

【问题讨论】:

  • l.preventDefault();移到此行del($(this));之前。也许actualizarCesta($(this)); 会导致问题?那个函数里有什么?
  • 抱歉,我已将函数 actualizarCesta() 的名称更改为 updateBasket()。我翻译了我的函数名称以便更容易理解,但我忘了翻译那个名称。
  • 我已经移动了l.preventDefault(),但还是有同样的问题,它几乎可以工作,但有时会失败。
  • 您期望它代表一个布尔值,并且仅在它为 true... 时才调用它... 似乎是一个非常奇怪的实现。你能指出一个实际应用这种技术的例子吗?
  • 用这个l.preventDefault(); 替换l.preventDefault() ? l.preventDefault() : l.returnValue = false; 是否正常工作?

标签: javascript jquery html ajax preventdefault


【解决方案1】:

1- e.preventDefault() 应该是第一个调用的函数。

2- IE 对此有不同的语法:

 event.returnValue = false;

检查here

【讨论】:

  • 谢谢莫森。 d,但现在它很奇怪,因为它在 IE 和 Chrome 中几乎可以正常工作,但在 Firefox 中仍然无法正常工作。 Firefox 的问题在于它遵循链接。不得不说,有时候不行,有可能吗?
  • 很抱歉之前没有发布过。我已经编辑了代码,它现在可以在所有浏览器中使用,尽管有时我在链接中单击两次以从购物篮中删除元素。我在 php 中的代码基于 jcart 代码,它使用它的方法创建一个对象购物车。该对象工作正常,它的方法也很好,但在 jcart 实现中不需要使用 jquery 'updateBasket()' 函数,实际上更新是自动的,但我不太了解它的完成方式,所以我自己做了用我自己的方式做。
  • .preventDefault() has been normalized by jQuery 所以你不需要额外的代码或 IE 的特殊语法。
  • 如果我使用 stopPropagation()??还是 stopImmediatePropagation()?
猜你喜欢
  • 2011-09-18
  • 2011-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多