Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - binding data to attribute by iterating

I have the following ForEach in my razor where i am setting some values. It works fine. I can see my all values.

 @foreach (var item in Model.ConsultantDetails.ScopeOfSevrices)
     {
      <div id="optionValue" class="item" data-value=>@item.Name</div>
    }

Then i have an ajax call and get the result back. I want to set this data back to same DIV by iterating

 $.each(data.ConsultantDetails.ScopeOfSevrices, function (index) {
   $('optionValue').attr("data-value=>", data.ConsultantDetails.ScopeOfSevrices[index].Name);
  });

No luck, how do i achieve that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. use for loop instead of foreach, so we can set seprate id to each iteration
  2. dont use data-value=> , instead use data-value=" " or some dummy value (here we use : item.Name)

    @for (int i = 0; i < Model.ProductTypeService.Count; i++)
      {
       var item = Model.ProductTypeService[i];
       var id = "optionValue" + i;
       <div id="@id" class="item" data-value="@item.Name">@item.Name</div>
      }
    
  3. finally, in jquery, we can assign attribute value based on div id

     $.each(data.ProductTypeService, function (index) {
                $('#optionValue' + index).attr("data-value", data.ProductTypeService[index].Name + index);  //  + index // just to see different value
            });
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...