使用 javascript / jquery 闭包在 ul >li 层次结构中级联值
我有 ul >力> ul>礼等级制度。每个 li 都有与其关联的输入文本框。我想将 onchange 事件处理程序附加到每个输入元素,以便当该元素更改时,所有后续子输入元素也继承该值。我想在每个元素最里面的 .bind 函数周围实现一个闭包,以便我可以在运行时传入父输入值。如何最好地实现这一点?
var $generatedFeatureTree = $('.generated','#feature_weights');
// Get all input text boxes in the top level div
var generatedWeights = $generatedFeatureTree.find('input[type="text"]');
for(var i =0; i< generatedWeights.length; ++i){
var $this = $(generatedWeights[i]);
var value = $this.val();
$this.bind('change',function(value){
$$this = $(this);
// get all children input elements of this node by traversing a parent 'li'
// and getting the lone 'ul' child
var children = $$this.parent('li').children('ul').find('input[type="text"]');
for(var j=0;j<children.length;++j){
$$$this = $(children[j]);
$$$this.val(value);
}
});
}
I have ul > li > ul > li hierarchy. Each li has input text box associated to it. I want to attach onchange event handlers to each input element so that when that element is changed all subsequent children input elements also inherit this value. I want to implement a closure around the innermost .bind function for each element so that I can pass in the parent input value on runtime. How best is this accomplished?
var $generatedFeatureTree = $('.generated','#feature_weights');
// Get all input text boxes in the top level div
var generatedWeights = $generatedFeatureTree.find('input[type="text"]');
for(var i =0; i< generatedWeights.length; ++i){
var $this = $(generatedWeights[i]);
var value = $this.val();
$this.bind('change',function(value){
$this = $(this);
// get all children input elements of this node by traversing a parent 'li'
// and getting the lone 'ul' child
var children = $this.parent('li').children('ul').find('input[type="text"]');
for(var j=0;j<children.length;++j){
$$this = $(children[j]);
$$this.val(value);
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许我误解了你想要什么,但我认为你有一个过度设计的解决方案。你就不能像这样做吗?
输入处于什么级别对您来说并不重要,您需要做的就是将低于该级别的所有输入设置为相同的值。因此,您可以将相同的更改函数附加到所有输入。我的函数只是查找与输入同级的
,查找该
中的所有文本框,并将它们设置为相同的值作为父文本框。我认为这就是您想要实现的目标。
这是一个现场演示:http://jsfiddle.net/Ender/wXqcE/
Maybe I'm misunderstanding what you want, but I think you have an overengineered solution there. Couldn't you just do it like this?
It doesn't really matter to you what level the input is at, all you need to be able to do is set all the inputs below that one to the same value. As such, you can attach the same change function to all the inputs. My function just looks for a
<ul>
that is a sibling to the input, finds all the textboxes in that<ul>
, and sets them to the same value as the parent text box. I think that's what you were looking to accomplish.Here's a live demo of that: http://jsfiddle.net/Ender/wXqcE/