Basically what I have here is a button that adds a new list item to an unordered list. Within this list item is a dropdown box (.formSelector) that when changed triggers an ajax call to get the values for another dropdown box (.fieldSelector) in the same list item.
The problem is on this line:
$(this).closest(".fieldSelector").append(
If I change it to
$(".fieldSelector").append(
the second box updates correctly. The problem with this is that when I have multiple list items it updates every dropdown box on the page with the class fieldSelector, which is undesirable. How can I traverse the DOM to just pick the fieldSelector in the current list item? Any help is greatly appreciated.
Complete code:
$("button", "#newReportElement").click(function() {
$("#reportElements").append("<li class=\"ui-state-default\"> <span class=\"test ui-icon ui-icon-arrowthick-2-n-s \"></span><span class=\"ui-icon ui-icon-trash deleteRange \"></span> <select name=\"form[]\" class=\"formSelector\"><? foreach ($forms->result() as $row) { echo "<option value='$row->formId'>$row->name</option>"; }?></select><select class=\"fieldSelector\" name=\"field[]\"></select></li>");
$(".deleteRange").button();
$('.formSelector').change(function() {
var id = $(this).val();
var url = "<? echo site_url("report/formfields");?>" + "/" + id;
var atext = "ids:";
$.getJSON(url,
function(data){
$.each(data.items, function(i,item){
$(this).closest(".fieldSelector").append(
$('<option></option开发者_如何转开发>').val(item.formId).html(item.formLabel)
);
});
});
});
return false;
});
this
has been lost in a barrage of callback functions. Inside your change()
handler, store a reference to the list element that originally initiated the event, then later reference it making use of closures.
Edit:
.fieldSelector
and .formSelector
are sibings and not parent/child. Since closest starts looking upwards in the hierarchy, it won't find anything. Instead use the siblings
method.
$('.formSelector').change(function() {
var listItem = $(this).siblings(".fieldSelector");
...
$.getJSON(...
$.each(...
listItem.append(...);
);
});
});
You're misunderstaning the .closest
method.
The .closest
method will return the innermost parent element matching a selector.
In addition, this
within the .each
loop will refer to the current item in the loop.
You should probably add var fieldSelector = $(something).find('.fieldSelector')
, where something
is an element that contains the correct .fieldSelector
.
For example, directly inside the change
handler, you could write $(this).siblings('.fieldSelector')
.
Please show us your HTML.
"Closest" will get the element ancestor, which is back up the tree. Since ".fieldSelector" is a sibling of ".formSelector", try using "next":
$(this).next(".fieldSelector")...
精彩评论