淘汰赛js自定义绑定

时间:2016-10-21 09:57:38

标签: javascript jquery knockout.js knockout-2.0

我正在使用Knockout js自定义绑定来绑定div中的一些新div元素,使用类,我从数据库获取数据,它只用于单个数据,如果数据不止一个,它再次获取绑定在我的下面的代码中,在同一个div中,

 //for single data it working 
<div data-bind="foreach:items">
  <ul data-role="listview">
  <li>
     <div databind="BindingImage({img:imageurl})" class="Image">
        <div id="img1"><img src=1.png /></div>
     </div>
  </li>
  </ul>
</div>

//for multiple data it not  working 
<div data-bind="foreach:items">
  <ul data-role="listview">
  <li>
    <div databind="BindingImage({img:imageurl})"class="Image">
        <div class="imageWrapper" id="img1"><img src=1.png /></div>
        <div clas="imageWrapper" id="img2"><img src=2.png /></div>
   </div>
        for multiple data its create databind="BindingImage div, but inside the div it does not bind anything, i need to bind image2 in this div but its getting bind on first  div itself,i need to bind first image inside the first BindingImage div and next  one in another BindingImage div where i am doing wrong. 
   <div databind="BindingImage({img:imageurl})"class="Image"></div>
  </li>
  </ul>
</div>


//custom binding//
ko.bindingHandlers.BindingImage = { 
    update: function(element, valueAccessor) {
        id+=1
        var className = element.className;
        imagewrapper= document.createElement('div');
        imagewrapper.className = "imageWrapper";
        imagewrapper.id = "img1"+id
        document.querySelector("." +className).appendChild(imagewrapper)
    }
};

1 个答案:

答案 0 :(得分:0)

有两个主要问题:

  • 首先,"<a>Email</a>"。这将始终返回id=+1。这与i = parseInt(1)相同。它应该是1
  • 第二个id+=1,这将始终附加到第一个容器。将其替换为document.querySelector("." +className).appendChild(imagewrapper)element.append(),考虑document.querySelectorAll("." +className)[id-1].appendChild(imagewrapper)将以1开头。

您还缺少id

的结束标记