backbone.js:渲染后将焦点设置为输入
我有一个有 1 个输入的模型。另外,我有一个收藏。现在,当我将模型添加到集合中时,我想将焦点设置为其输入。 准确地说,我需要将焦点设置在新创建的模型视图的输入上。
但是,我似乎无法让它发挥作用。这是我将模型视图添加到集合视图的函数:
addOne: function(InvoiceItem) {
var view = new InvoiceItemView({model: InvoiceItem});
this.$('tr[data-id="'+InvoiceItem.get('after')+'"]').after(view.render().el);
this.$('tr[data-id="'+InvoiceItem.cid+'"]').css('background', 'green');
this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
},
问题是,第三次调用: this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus( );
不执行任何操作。这很奇怪,因为我似乎只能对根元素 tr
进行 DOM 操作,除此之外什么也做不了。
在我看来,jQuery 不知道该元素存在,这很奇怪,因为当我执行 alert(this.$('tr[data-id="'+InvoiceItem.cid+'"] input' ).length)
我得到1,这表明该元素存在。
我在这里做错了什么?
I have a Model that has 1 input. Also, I have a Collection. Now, when I add a model to the collection, I want to set the focus to it's input.
To be precise, I need to set the focus on the newly created model view's input.
However, I can't seem to get it to work. Here's my function that adds the model's view to the collection view:
addOne: function(InvoiceItem) {
var view = new InvoiceItemView({model: InvoiceItem});
this.$('tr[data-id="'+InvoiceItem.get('after')+'"]').after(view.render().el);
this.$('tr[data-id="'+InvoiceItem.cid+'"]').css('background', 'green');
this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
},
The problem is, the third call: this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
does not do anything. And it's weird, because it seems that I can only do DOM manipulation on the root element tr
, and on nothing else besides that.
It seems to me that jQuery doesn't know that the element exists, which is weird, because when I do alert(this.$('tr[data-id="'+InvoiceItem.cid+'"] input').length)
I get 1, which indicates that the element exists.
What it is that I am doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 _.defer 解决了我的问题:
Using _.defer fixed my problem:
而不是
this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
尝试这个
Instead of
this.$('tr[data-id="'+InvoiceItem.cid+'"] input').focus();
try this
我遇到了与您的问题非常相似的问题,并在寻找解决方案时最终来到这里。您的帖子是几个月前的,所以您可能已经超越了这个,但希望这对其他人有帮助。我能够使用 jQuery 的
ready
函数处理程序解决问题。我一直认为它只能在document
上使用,但你也可以在子节点上使用它。试试这个:I had a problem very similar to yours and ended up here while searching for a solution. Your post was a few months ago so you probably have moved past this, but hopefully this will help someone else. I was able to solve the problem using jQuery's
ready
function handler. I always thought it could only be used on thedocument
but you can use it on subnodes as well. Try this: