首页 文章

Knockout数据绑定不适用于div元素[关闭]

提问于
浏览
0

我正在关注淘宝的一个教程当我将“foreach:lines”绑定到“tbody”元素时,代码工作正常 . 但是,如果我尝试将“foreach”绑定到div元素,它将失败并抛出错误 .

工作代码

<tbody data-bind="foreach:lines">           
  <tr>
<td width="25%">
            <select data-bind="options:$parent.products,value:product,optionsText:'shortDescription', optionsCaption:'Select a product ...'"></select>
    </td>
</tr>       
 </tbody>

但是,如果我用div包装tr并将data-bind =“foreach:lines”移动到div元素:

<tbody>
        <div data-bind="foreach:lines">           
        <tr>
            <td width="25%">
            <select data-bind="options:$parent.products,value:product,optionsText:'shortDescription', optionsCaption:'Select a product ...'"></select>
            </td>
        </tr>   
        </div>  
        </tbody>

使用上面的代码会抛出错误

Uncaught Error:无法解析bindings.Message:ReferenceError:$ parent未定义; Bindings值:

请让我知道如何绑定foreach与div不同于tbody元素

1 回答

  • 1

    div 不是 tabletbody 的有效子项,没有浏览器实际上会以这种方式呈现它 . 例如,Chrome会将 div 放在 table 之前(而不是您想要的表格内) .

    <div data-bind="foreach: lines"></div>
    <table>
        <tbody>
            <tr>
                <td width="25%">
                    <select data-bind="options:$parent.products,value:product,..."></select>
                </td>
            </tr>
        </tbody>
    </table>
    

    select 元素的上下文中, $parent 不存在,因此出错 .

    使用有效的html和knockout将起作用 .


    如果您想以这种方式重复这些行,则必须使用containerless controls . 评论几乎可以放在任何地方,比如这里 .

    <table>
        <tbody>
            <!-- ko foreach: lines -->
                <tr>
                    <td width="25%">
                        <select data-bind="options:$parent.products,value:product,..."></select>
                    </td>
                </tr>
            <!-- /ko -->
        </tbody>
    </table>
    

相关问题