cascading values in a ul >li hierarchy with javascript / jquery closure
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 开发者_C百科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);
}
});
}
Maybe I'm misunderstanding what you want, but I think you have an overengineered solution there. Couldn't you just do it like this?
var myInputs = $('input[type=text]'); //use whatever selector you need to grab ALL textboxes
myInputs.change(function() {
$(this).siblings('ul').find('input[type=text]').val($(this).val());
});
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/
精彩评论