我有一个地址查找器系统,用户输入邮政编码,如果邮政编码被验证,然后返回并显示地址列表,然后他们选择地址行,列表消失,然后地址行被进一步拆分成某些表格输入.
我面临的问题是,当他们通过上述过程然后清除邮政编码表单字段,点击查找地址按钮并重新显示地址列表.
事件虽然列表和父tr已从DOM中删除但它仍然报告它以长度1存在?
我的代码如下:
jQuery的
// when postcode validated display Box var $addressList = $("div#selectAddress > ul").length; // if address list present show the address list if ($addressList != 0) { $("div#selectAddress").closest("tr").removeClass("hide"); } // address list hidden by default // if coming back to modify details then display address inputs var $customerAddress = $("form#detailsForm input[name*='customerAddress']"); var $addressInputs = $.cookies.get('cpqbAddressInputs'); if ($addressInputs) { if ($addressInputs == 'visible') { $($customerAddress).closest("tr").removeClass("hide"); } } else { $($customerAddress).closest("tr").addClass("hide"); } // Need to change form action URL to call post code web service $("input.findAddress").live('click',function(){ var $postCode = encodeURI($("input#customerPostcode").val()); if ($postCode != "") { var $formAction = "customerAction.do?searchAddress=searchAddress&custpc=" + $postCode; $("form#detailsForm").attr("action",$formAction); } else { alert($addressList);} }); // darker highlight when li is clicked // split address string into corresponding inputs $("div#selectAddress ul li").live('click',function(){ $(this).removeClass("addressHover"); //$("li.addressClick").removeClass("addressClick"); $(this).addClass("addressClick"); var $splitAddress = $(this).text().split(","); $($customerAddress).each(function(){ var $inputCount = $(this).index("form#detailsForm input[name*='customerAddress']"); $(this).val($splitAddress[$inputCount]); }); $($customerAddress).closest("tr").removeClass("hide"); $.cookies.set('cpqbAddressInputs','visible'); $(this).closest("tr").fadeOut(250,function() { $(this).remove(); }); });
解决方法
我想你遇到了我最近遇到的同样问题.如果你有一个指向5 DIV的变量(例如:var divs = $(‘.mydivs’);)然后你在其中一个DIV上调用jQuery的remove(),就像这样:divs.eq(0).remove( )你会看到divs.size()仍然返回5个项目.这是因为remove()在DOM上运行.但是……如果在调用remove()之后再重新设置你的变量:divs = $(‘.mydivs’);并获得您现在将获得正确大小的数组大小.我添加了以下显示的示例代码:
// get all 5 divs var d = $('.dv'); // remove the first div d.eq(0).remove(); // you would expect 4 but no,it's 5 alert(d.size()); // re-set the variable d = $('.dv'); // Now we get 4 alert(d.size());