淘汰赛数据绑定不适用于div元素 [英] Knockout data-bind doesnot work on div element

查看:68
本文介绍了淘汰赛数据绑定不适用于div元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注淘汰赛的教程之一.当我将"foreach:lines"绑定到"tbody"元素时,代码可以正常工作.但是,如果我尝试将"foreach"绑定到div元素,它将失败并引发错误.

I am following one of the tutorials of knockout The code works fine when i bind "foreach:lines" to "tbody" element. However, if i try binding "foreach" to a div element, it fails and throws an error.

工作代码

<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元素:

However, if i wrap the tr with a div and move data-bind="foreach:lines" to the div element:

<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>

上面的代码会引发错误

未捕获的错误:无法解析绑定消息:ReferenceError:未定义$ parent;绑定值:

Uncaught Error: Unable to parse bindings.Message: ReferenceError: $parent is not defined;Bindings value:

请让我知道将foreach绑定到div与tbody元素有何不同

Please let me know how is binding foreach to div different from tbody element

推荐答案

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

A div is not a valid child of a table or tbody, no browser will actually render it that way. Chrome for instance will place that div before the table (and not within your table as you wanted).

<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不存在,因此会出现错误.

In the context of the select element, $parent does not exist, hence the error.

使用 valid html并删除即可.

Use valid html and knockout will work.

如果您想以这种方式重复这些行,则必须使用

If you wanted to repeat those rows that way, you would have to use containerless controls. Comments can be placed almost anywhere, like here.

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

这篇关于淘汰赛数据绑定不适用于div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆