jquery链接无法正常工作

时间:2012-06-21 11:12:13

标签: jquery

在提交主报价单之前,我有以下代码插入多个产品和价格。

$(document).ready(function(){

    var counter = 2;

    $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<br>' + '<label>Product '+ counter + '  </label>' +
          '<input type="text" name="product" id="product" value="" >' + 
          '<label>Price '+ counter + '  </label>' +
          '<input type="text" name="price" id="price"  value="" >'+ '<a href="#" id="save" >Save!</a>');

    newTextBoxDiv.appendTo("#TextBoxesGroup");

    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   
    counter--;
        $("#TextBoxDiv" + counter).remove();
     });

     $("#getButtonValue").click(function () {

    var msg = '';
    for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
    }
          alert(msg);
    });

    $("#save").click(function() {

        if(!$("#product").val() || !$("#price").val() ){
            apprise("You must define a product and price!");
            }else{
            var product = $("#product").val();
            var price = $("#price").val();
            var postdata = 'product='+product+'&price='+price;

            $.ajax({  
                type: "POST",  
                url: "inserter/add_quotation_product.php",  
                data: postdata, 
                success: function() {  
                    $('#TextBoxesGroup').html("<div id='message'></div>");  
                    $('#message').html(product+" Saved!");  
                }  
            });  
            return false;  

        }

主要HTML代码:

<div id='TextBoxesGroup'> 
    <div id="TextBoxDiv1"> 
        <label>Product 1 </label> 
        <input type=text 
                id="product" 
                name="product" 
                placeholder="product to quote" 
                required/> 
        <label>Price 1</label> 
        <input id="price" 
                name="price" 
                type=text 
                placeholder="price of product" 
                required> 
            <a href="#" id="save" >Save!</a> 
    </div> 
</div>

问题是单击手动创建的保存按钮效果不错但单击jquery创建的保存按钮似乎完全无效!

2 个答案:

答案 0 :(得分:0)

您应该使用.on()方法将点击处理程序委派给新按钮(而不是弃用的.live()方法)。

http://api.jquery.com/on

像:

$("#yourButtonParent").on('click', '#yourButton', function () {

    // code here

});

答案 1 :(得分:0)

已保存链接的点击事件已绑定。添加新产品时,您无需附加事件即可创建新的保存链接。

您不能拥有具有相同ID的多个元素链接,因此我会将一个类分配给保存链接。它必须位于主html代码和创建链接的javascript代码中。

<a href="#" class="save">Save!</a>

使用jquery对象的live方法来绑定事件以便将来&#39;事件也是如此。 http://api.jquery.com/live/

$(".save").live("click", function() {
});

取决于您必须使用的jquery版本:http://api.jquery.com/on

相关问题