如何在jquery中重新绘制逻辑?

时间:2014-01-16 12:43:44

标签: javascript jquery replace iteration element

我有一个如下所示的div结构,

<div id-"itemsRows">
  <ul id="row1">
          <input type="hidden" id="hfId" value="1" />
        <input type="hidden" id="hfOrd" value="2" />
        <input type="hidden" id="hfDate" value="3" />
       <li class="popup"> <div id="p1"></div> <div id="p2"></div></li>
  </ul>
 <ul id="row2">
       <input type="hidden" id="hfId" value="4" />
        <input type="hidden" id="hfOrd" value="5" />
        <input type="hidden" id="hfDate" value="6" />
       <li class="popup"> <div id="p2"></div> <div id="p2"></div> </li>
  </ul>
 <ul id="row3">
       <input type="hidden" id="hfId" value="2" />
        <input type="hidden" id="hfOrd" value="3" />
        <input type="hidden" id="hfDate" value="4" />
       <li class="popup"> <div id="p3"></div> <div id="p3"></div></li>
  </ul>
</div>

现在我有一个html通过ajax调用看起来像这样,

<ul id="ajaxrows">
<li>
  <input type="hidden" id="hfId" value="1" />
            <input type="hidden" id="hfOrd" value="2" />
            <input type="hidden" id="hfDate" value="3" />
  <div id="p11"></div> <div id="p12"></div>
</li>
<ul>
<ul id="ajaxrows">
<li>
      <input type="hidden" id="hfId" value="4" />
            <input type="hidden" id="hfOrd" value="5" />
            <input type="hidden" id="hfDate" value="6" />
  <div id="p22"></div> <div id="p32"></div>
</li>
<ul>

现在我必须比较这两个结构并匹配所有的隐藏字段值。如果所有三个匹配我必须用ajaxrows中的div替换UL row1中的两个div。任何想法如何在jquery中完成这个?

2 个答案:

答案 0 :(得分:2)

这应该给你一个开始

$('#itemsRows ul').each(function () { // go thru row uls
    var $this = $(this);

    var rows_arr = $(this).find('input').map(function () { // create an array with the input
        return this.value;
    }).get();

    $('#wrap-ajax ul').each(function () { // I wrapped this in a div to better loop it
        var ajx_arr = $(this).find('input').map(function () {
            return this.value;
        }).get();

        if (rows_arr.toString() === ajx_arr.toString()) { // lazy meh way to compare arrays
            console.log(rows_arr, ajx_arr);
            $(this).find('div').appendTo($this.find('li.popup').empty()); // delete the old and put the new
        }

    });

});

FIDDLE

答案 1 :(得分:0)

我假设数字块相同,每个块中的输入数量相同。

 $($("#itemsRows ul")).each(function( index ){   
        var ajaxResult = $($("#ajaxrows li"))[index];
        var count =0;
        $($(this).find("input")).each(function( index2 ){
            var res = $(ajaxResult).find("input")[index2];
            if($(this).val() ==  $(res).val()){
                count++;
            }
        });


        var ajaxResultDivs = $($("#ajaxrows li")[index]).find("div");
        if(count == $(this).find("input").length){
             $($(this).find("div")).each(function( index ){   
               $(this).replaceWith($(ajaxResultDivs));              
            });
        }                        

    });

console.log($("#itemsRows"));

FIDDLE