以下是我的HTML

<div id="ingredientrow1">
    <div id="add"><a href="#" id="addIngredient1">Add</a></div>
    <div id="remove"><a href="#" id="removeIngredient1">Remove</a></div>
    <div id="si">
      <input type="text" id="singleIngredient1" name="single_ingredient" />
      <input type="hidden" id="recipe_ingredient_id1" name="recipe[new_ri_attributes][][ingredient_id]" />
    </div>
    <div id="iq"><input type="text" id="recipe_ingredient_quantity" name="recipe[new_ri_attributes][][quantity]" class="txt_qty" /></div>
    <div id="iss"><select id="recipe_ingredient_serving_size_id1" name="recipe[new_ri_attributes][][serving_size_id]" ></select></div>
  </div>

我克隆了div“ingredientrow1”。并且我将所有id增加一,所以现在我的HTML有两个id为id的div:&quot; ingredientrow1&quot;和“ingredientrow2”。用户可以通过单击id为“addIngredient1”的锚来克隆此div任意数量的时间。

注意:所讨论的选择控件的id为“recipe_ingredient_serving_size_id1”&quot;也改变了... id2。

我还在控件“singleIngredient1”上使用自动完成插件。这将设置隐藏输入中所选成分的ID,并在选择框中填充服务大小。

问题:由于用户可以生成n个ingredientrow div,我不知道选择成分时要填充哪个选择框。

已知事实:我确实知道用户正在使用哪种内容。我得到这样的

var recipeingredientid = $(this).next()。attr(&quot; id&quot;);

这给了我“ingredientrown”其中n是1,2,....

我的问题:如何访问特定ingredientrow中的recipe_ingredient_serving_size_idn选择框?由于选择ID已更改。

我的问题的例子:如果我的配方是“ingredientrow2”,那么我的配方就是“ingredientrow2”。那么select控件的id将以2结尾。如何获得对该select控件的引用?

这是我的JQuery,当用户从自动完成输入中选择一个成分时运行

$("input[id*='singleIngredient']").result(function(event, data, formatted) {

    if (data) {

      var recipeingredientid = $(this).next().attr("id");
      $("#" + recipeingredientid).val(data[1]);

      $.getJSON("/serving_sizes?ingredientid=1", function(j) {

        var options = "<option value=''>Please select a serving size</option>";
 for (var i=0; i < j.length; i++)
   options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';

//I am trying not to hard code this id here.
 $("#recipe_ingredient_serving_size_id1").html(options);
      });
    }

  });

我知道我总是传递1作为ingredientid但这只是一个测试......

感谢您的时间。

有帮助吗?

解决方案

您无需知道选择框的确切ID即可找到它。

例如,如果您知道您在其中工作的div是 ingredientrow1 ,那么您可以只对该div内的选择框进行查询。

看起来像这样:

var container_id  = 'ingredientrow1';
var $select_box = $(container_id).find('select[id^=recipe_ingredient_serving_size_id]');

此时您有选择框,可以根据需要进行操作。如果需要获取元素的id,可以在container_id的子字符串上执行parseInt。这看起来像这样:

var container_id  = 'ingredientrow1';
var id_prefix     = 'ingredientrow';
var prefix_length = id_prefix.length;
var id_num        = parseInt( container_id.substring(prefix_length) ,10);

doSomething(data[id_num]); // this is hypothetical...

您的问题有点难以理解,但希望这是相关信息。祝你好运。

其他提示

$(this)
  .parents("[id^='singleIngredient']")
  .find("[id^='recipe_ingredient_serving_size_id']")

鉴于recipe_ingredient_serving_size是一个选择框,并且是容器中唯一的选择框,以下内容应该有效。

$(this).parent().find('select').html(options)

那应该把你排除在外。如果您最终选择了多个,则可以给它一个类并使用它来选择它。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top