Knockout.js获取与数据关联的dom对象 [英] Knockout.js get dom object associated with data
问题描述
示例:
< ul data-bind =foreach:Item>
< li data-bind =events:{click:getDomObject},text:'text:'+ text>
< / li>
< / ul>
在 getDomObject
函数中,我想以获得具体的< li>< / li>
DOM对象,以便我可以使用它进行一些jQuery操作。
我已经考虑在Item ViewModel中添加一个 id
成员,然后添加id作为行项目的html id,然后根据该选项添加,但我觉得应该有一个更简单的方法。
引用由knockout.js生成的动态HTML的正确方式是什么?
事件处理程序,如点击获取传递两个参数。那就是a)这个事件所属的项目,就像你用foreach绑定(在你的情况下为Item)呈现的可观察数组的条目一样。和b)事件对象,它为您提供有关实际事件的更多信息。该对象包含点击的DOM元素(键target):
getDomObject = function(item,event){
var $ this = $(event.target);
// ...
}
只是一个注释:不要混合淘汰和本地jQuery DOM操作 - 如果您可以通过巧妙的敲除绑定实现相同的结果,我会建议继续使用。
这里是一个简单的演示: a href =http://jsfiddle.net/KLK9Z/213/ =noreferrer> http://jsfiddle.net/KLK9Z/213/
I'm working with knockout.js to build dynamic lists and I'm trying to figure out how I can get the DOM object associated with an object in my observable array. Specifically I want to get the jQuery for a row.
Example:
<ul data-bind="foreach: Item">
<li data-bind="events: {click: getDomObject}, text: 'text: ' + text">
</li>
</ul>
in the getDomObject
function, I would like to be able to get the specific <li></li>
DOM object so that I can do some jQuery manipulation with it.
I've thought about adding an id
member to the Item ViewModel and then add the id as the line item's html id and then select based on that, but I feel that there should be an easier way.
What is the proper way to reference the dynamic HTML generated by knockout.js?
Event handlers like click get passed two arguments. That is a) the item that this event belongs to - like the entry of an observable array that you're rendering with the foreach binding ("Item" in your case). And b) an event object, that provides you with more information about the actual event. This object contains the DOM element that got clicked on (key "target"):
getDomObject = function(item, event) {
var $this = $(event.target);
// ...
}
Just a note: Don't mix knockout and native jQuery DOM manipulations - if you can achieve the same result with clever knockout bindings, I would recommend going with that.
And here is a simple demo: http://jsfiddle.net/KLK9Z/213/
这篇关于Knockout.js获取与数据关联的dom对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!