jQuery preventDefault并不总是有效

时间:2014-11-13 10:01:56

标签: javascript jquery html ajax preventdefault

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

我的问题是,在此菜单中,我有一个与每个项目相关的链接列表,允许您删除所选项目。这个链接在某个时候运行良好,并且根据我使用的Web浏览器而不同地工作。

我想要的是删除项目而不刷新所有网页,所以我想我必须对链接进行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代码我不会发布所有内容,但我会发布最相关的代码:

class 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();
}

为了更好地了解我得到的东西,我还展示了一张照片:

enter image description here

我对代码的启发来自以下代码:

http://conceptlogic.com/jcart/

1 个答案:

答案 0 :(得分:0)

1- e.preventDefault()应该是第一个打电话的功能。

2- IE有不同的语法:

 event.returnValue = false;

检查here