删除动态创建的行 - 我需要在哪里放置委托()?

时间:2012-05-02 18:59:39

标签: jquery dynamic delegates

我继承了一些不太有用的代码......

我有一个jsp,其中列出了一个对话框:

<div class="ShippingPoints">
    <div id="dialog-form" title="Shipping Points">
        <p class="validateTips">
            Please include all vendor ship points by product group. If vendor
            ships all products from one location input City, State, Zip Code
            then select "All" for product group.
        </p>

        <fieldset>
            <label font-family="Courier New" align="left" for="city">City</label>
            <input maxlength=50 align="right" type="text" name="city" id="city"
                class="text ui-corner-all" />
            <br />
            <label font-family="Courier New" align="left" for="state">State</label>
            <select maxlength=6 align="right" name="state" id="state"
                class="text ui-corner-all">
                <c:forEach items="${states}" var="state">
                    <option value="${state.fieldValue}">
                        ${state.fieldDescription}
                    </option>
                </c:forEach>
            </select>
            <br />
            <label font-family="Courier New" align="left" for="stateOther">State (Other):</label>
            <input maxlength=6 align="right" type="text" name="stateOther" id="stateOther" value=""
                class="text ui-corner-all" />
            <br />
            <label font-family="Courier New" align="left" for="zip">Zip</label>
            <input align="right" maxlength=10 align="right" type="text" name="zip" id="zip" value=""
                class="text ui-corner-all" />
            <br />
            <label font-family="Courier New" align="left" align="left" for="product">Product</label>
            <input align="right" maxlength=50 type="text" name="product" id="product" value=""
                class="text ui-corner-all" />
            <br />
        </fieldset>
    </div>

在页面上,我有一个打开对话框的链接......以及一个调用删除...

的链接
<table id="shipPoints" class="ui-widget" width="697">
    <tr width="695">
    <td width="395"><a href="#" id="add-shipping-point"> Add Shipping Point </a></td>
    <td width="300">Click <img src="<%= request.getContextPath() %>/images/delete.gif"       onclick="deleteShippingPoints('shipPoints')" /> to remove checked shipping points</td>
</tr>           
</table>

调用此jquery函数

$j("#add-shipping-point").click(function() {
    $j("#dialog-form").dialog("open");
    return false;
});

以下是对话框的完整代码

$j(function() {
$j("#dialog:ui-dialog").dialog("destroy");

var city = $j("#city"), state = $j("#state"), zip = $j("#zip"), product = $j("#product"), allFields = $j(
        []).add(city).add(state).add(zip).add(product), tips = $j(".validateTips");

function updateTips(t) {
    tips.text(t).addClass("ui-state-highlight");
    setTimeout( function() {
        tips.removeClass("ui-state-highlight", 1500);
    }, 500);
}

function checkLength(o, n, min, max) {
    if (o.val().length > max || o.val().length < min) {
        o.addClass("ui-state-error");
        updateTips("Length of " + n + " must be between " + min + " and "
                + max + ".");
        return false;
    } else {
        return true;
    }
}

function checkRequired(o, n) {
    if (o.val().length == 0) {
        o.addClass("ui-state-error");
        updateTips(n + " is a required field.");
        return false;
    } else {
        return true;
    }
}

function checkRegexp(o, regexp, n) {
    if (!(regexp.test(o.val()))) {
        o.addClass("ui-state-error");
        updateTips("Zip Code is not in proper format.");
        return false;
    } else {
        return true;
    }
}

$j("#dialog-form")
    .dialog(
    {
    autoOpen : false,
    height : 500,
    width : 500,
    modal : true,
    buttons : {
            "Add Shipping Point" : function() {
            var bValid     = true;
            var cityValid  = true;
            var stateValid = true;
            var zipPresent = true;
            var zipValid   = true;

            updateTips("");
            allFields.removeClass("ui-state-error");

            cityValid  = checkRequired(city, "City");
            stateValid = checkRequired(state, "State");
            zipPresent = checkRequired(zip, "Zip");
            if(zipPresent) { zipValid   = checkRegexp(zip, /(^\d{5}$)|(^\d{5}-\d{4}$)/, "Zip Code"); }

            bValid     = cityValid && stateValid && zipPresent && zipValid;

    if (bValid) {
        // make Ajax call save the Shipping Point and add to the list
        var shipPointId = saveShippingPoint();

        // alert(shipPointId);

        if (shipPointId == "na") {
            alert("There was a problem adding the Shipping Point.  Please try again.  
            If the problem persists please contact support.");
        } else {
            $j("#shipPoints tr:last").after(                                                                                        
                "<tr>"
                + "<td>"
                + city.val()
                + ", "
                + state.val()
                + "</td>"
                + "<td>"
                + "<INPUT type='checkbox' NAME='chk' VALUE='"
                + shipPointId
                + "' />"
                + "</td>"
                + "</tr>");
        }
        $j(this).dialog("close");
    }
},
Cancel : function() {
$j(this).dialog("close");
    }
},
close : function() {
    allFields.val("").removeClass("ui-state-error");
}
});

$j("#add-shipping-point").click(function() {
    $j("#dialog-form").dialog("open");
    return false;
});
});

问题是你可以动态地向表中添加行,然后如果你选中复选框并删除一个新创建的行,它会 不删除。基本上是因为对删除装运点的调用传递了空白ID。

我已经读过它,我意识到我必须使用委托将事件绑定到新创建的角色。然而,我所拥有的语法似乎并不存在 与网上的内容完全匹配,所以我不确定在哪里指定代表?

有人有什么想法吗?

保存和删除代码如下

<script>
// Ajax call to add the Shipping Point to the Session
function saveShippingPoint() {

    var savedId = "";

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            savedId = xhr.responseText;
            // alert(savedId);
        }
    };      
    var url = '<portlet:resourceURL id="saveShippingPoint"/>';
    xhr.open("GET", url + 
       "?city=" + $j( "#city" ).val() +
       "&state=" + $j( "#state" ).val() +
       "&stateOther=" + $j( "#stateOther" ).val() +
       "&zip=" + $j( "#zip" ).val() +
       "&product=" + $j( "#product" ).val()
       , true);
    xhr.send();

    // alert(savedId);
    return savedId;
}

// A function to delete rows from the Shipping Points table

function deleteShippingPoints(tableID) {
var xhr = new XMLHttpRequest();

var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var shippingPointsId = "";

for ( var i = 0; i < rowCount; i++) {
    var row = table.rows[i];
    var chkbox = row.cells[1].childNodes[0];

    if (null != chkbox && true == chkbox.checked) {
        shippingPointsId = shippingPointsId + chkbox.value + ",";
        table.deleteRow(i);
        rowCount--;
        i--;
    }
}

var url = '<portlet:resourceURL id="deleteShippingPoint"/>';
xhr.open("GET", url + "?shippingPointsId=" + shippingPointsId, true);
xhr.send();
}
</script>

2 个答案:

答案 0 :(得分:1)

.delegate()的技巧是你必须将它绑定到页面上已经存在的容器。保证这一点的一种方法是执行$(document).delegate('.myelement', 'click', myhandler);,使其功能类似于.live()。但是,如果您想获得更高性能,请选择一个更接近您要绑定到的元素的容器:

$('#mypermanentcontainer').delegate('.mydynamicthing', 'myevent', myhandler);

<强>更新

所以看看你的代码就是这一行:$j(function() { ... });。我假设您使用$j作为$jQuery的别名。如果是这样,$j(function() {});$j(document).ready(function(){});完全相同,这是在DOM准备就绪时运行的代码(在jQuery中称为“文档就绪”)。这通常是发生事件绑定的地方。你已经有了一些,你的整个$j("#dialog-form").dialog(...)部分是在document.ready函数中发生的事件连线。

所以,只需将所有剩余的事件接线放在那里,你应该好好去!

答案 1 :(得分:1)

将jquery更改为此

$j(function() {
$j("#dialog:ui-dialog").dialog("destroy");

$j("#shipPoints2").delegate(".delete-shipping-points", "click", function () {
var xhr = new XMLHttpRequest();

var table = document.getElementById('shipPoints');
var rowCount = table.rows.length;
var shippingPointsId = "";

for ( var i = 0; i < rowCount; i++) {
    var row = table.rows[i];
    var chkbox = row.cells[1].childNodes[0];

    if (null != chkbox && true == chkbox.checked) {
        shippingPointsId = shippingPointsId + chkbox.value + ",";
        table.deleteRow(i);
        rowCount--;
        i--;
    }
}

var url = '<portlet:resourceURL id="deleteShippingPoint"/>';
xhr.open("GET", url + "?shippingPointsId=" + shippingPointsId, true);
xhr.send();
} );

(休息与以前相同)

和JSP到此

<div id="shipping-points-contain">
<table id="shipPoints" class="ui-widget-content" width="697">
<thead>
<tr class="ui-widget-content"  width="696">
        <th class="ui-widget-header" width="395">
    Shipping Points
    </th>
        <th class="ui-widget-header" width="300">
    Remove
    </th>
</tr>
</thead>
<tbody>
<c:forEach items="${shippingPoints}" var="shippingPoint">
<tr width="695">
    <td with="395">
        ${shippingPoint.shippingPointsCity},
        ${shippingPoint.shippingPointsState}
    </td>
    <td width="300">
    <INPUT type="checkbox" NAME="chk" value="${shippingPoint.shippingPointsId}" />
    <INPUT type="hidden" NAME="shipPointId" VALUE="${shippingPoint.shippingPointsId}" />
    </td>                           
</tr>
</c:forEach>
</tbody>
</table>
<table id="shipPoints2" class="ui-widget" width="697">
<tr width="695">
<td width="395"><a href="#" id="add-shipping-point"> Add Shipping Point </a></td>
<td width="300">Click <a href="#" id="delete-shipping-points"> <img src="<%= request.getContextPath() %>/images/delete.gif"  /></a>  remove checked shipping points</td>
</tr>           
</table>
</div>

至少我没有得到任何语法错误,页面显示正常并且添加仍然有效,但是当我点击图像时没有触发删除,所以事件绑定还没有...... < / p>