結果に基づいて選択ボックスを変更する ajax 呼び出しを行っています。私が抱えている問題は、dom 要素に ajax 呼び出し内のスコープがないため、その兄弟を見つけてデータで変更できないことです。明確にするために、以下のhtmlを見てください
<div class="field_group">
<select name="example1">
<option value="something">something</option>
</select>
<select name="example2">
<option value="something">something</option>
</select>
</div>
基本的に、例 1 が変更されると、例 2 のデータが変更されます。このページのすべてのフィールドは動的に選択され、0 から 1000 のフィールドが存在する可能性があるため、何らかの状況下で何らかのダイレクト セレクターを使用して問題を回避できないことに注意することが重要です。以下は私の実際のコードです
$(".landscape_type").on('change',function(){
var my_landscape_type = $(this);
console.log($(this).val());
var product_category = $(this).val();
$.post('/quotes/ajax_get_quote_products/'+product_category, function(data,my_landscape_type) {
var data_object = JSON.parse(data);
console.log(data_object);
console.log('should output here');
console.log(my_landscape_type.val());
if(data_object["error"]) {
alert(data_object["error"]);
my_landscape_type.parents('.field_group').children(".landscape_product").empty();
my_landscape_type.parents('.field_group').children(".landscape_product").append("<option selected='selected' value='-1'>No Products Found!</option>");
} else {
my_landscape_type.parents('.field_group').children(".landscape_product").empty();
my_landscape_type.parents('.field_group').children(".landscape_product").append("<option selected='selected' value='-1'>Select a Product...</option>");
for (index in data_object) {
my_landscape_type.parents('.field_group').children(".landscape_product").append("<option value='"+data_object[index]["product_id"]+"'>"+data_object[index]["product_name"]+"</option>");
console.log(data_object[index], index);
}
}
});
});
ここに出力する必要があるという行の下を見ると、my_landscape_type の値を取得する必要がある場所がわかりますが、取得できないため、スコープが失われ、そのままでは機能しません。