为什么我不能正确地通过车把元素进行迭代?

时间:2019-06-02 09:59:30

标签: jquery html handlebars.js frontend web-frontend

我正在使用jQuery和AJAX和Handlebars.js为网站编写前端代码。 我有HTML,CSS和script.js文件。 我对Javascript和技术非常陌生。这是我第一次在代码中使用把手。

我使用JSON解析来解析URL中提供的全部数据。

类似

{"products": 
[{"id": 0, 
   "name": "Ocean Blue Shirt",
   "description": "<p>Ocean blue cotton shirt with a narrow collar and 
                      buttons down the front and long sleeves. Comfortable 
                      fit and tiled kalidoscope patterns. </p>", 
   "category": "men", 
   "image_url": "https://burst.shopifycdn.com/photos/young-man-in-bright- 
                 fashion_925x.jpg", 
   "unit_cost": 92.95, 
   "inventory": 0},  

 {"id": 1, 
  "name": "Classic Varsity Top",
  "description": "<p>Womens casual ......}
  ..
  ..
  ]}

我已经创建了按钮,并使用{{name}}创建了多个具有重复名称的按钮。我的目标是使每个按钮在单击时都以“模式”视图包含各自的{{description}}。

我已经能够实现第一个按钮(使用{{name}}命名),当我单击该按钮时,它显示为从“ Ocean blue cott .....”开始的描述,但是我无法如果我单击其他任何按钮(带有其他{{name}}的按钮,则得到任何信息。

请仔细看一下代码,帮助我找出问题所在,谢谢!

script.js

    var myRequest = new XMLHttpRequest()
    myRequest.open('GET' , 'http://127.0.0.1:8010/products' )
    myRequest.onload = function() {

            var myData = JSON.parse(myRequest.responseText)

            createHTML(myData)

                // Get the modal
                var modal = document.getElementById("myModal")
                // Get the button that opens the modal
                var btn = document.getElementById("myBtn")

                // Get the <span> element that closes the modal
                var span = document.getElementsByClassName("close")[0]

                // When the user clicks on the button, open the modal

                btn.onclick = function() {
                 modal.style.display = "block"
                }

                // When the user clicks on <span> (x), close the modal
                span.onclick = function() {
                  modal.style.display = "none"
                }


    }
            myRequest.send()

            function createHTML(data) {

            var template = document.getElementById("prodTemp").innerHTML
            var compiledTemplate = Handlebars.compile(template)
            var genHTML = compiledTemplate(data)

            var prodContainer = document.getElementById("prod-container")
            prodContainer.innerHTML = genHTML

    }

index.html

   {{#each products}}

                                <tr>

                                    <td>

                                        <!-- Trigger/Open The Modal -->
                                        <button id="myBtn">{{name}}</button>


                                        <!-- The Modal -->
                                        <div class = "modal" id="myModal" >
                                          <!-- Modal content -->
                                          <div class="modal-content">
                                            <span class="close">&times;</span>
                                              <li  >Product Description: {{{description}}}</li>
                                          </div>
                                        </div>
                                    </td>
                                    <td>
                                        ${{unit_cost}}
                                    </td>
                                </tr>
                            {{/each}}

2 个答案:

答案 0 :(得分:0)

模态的

ID是触发模态的原因。如果所有模态元素具有相同的ID,则按钮将不知道触发谁。

Future< List<double>> getLocation() async {
  location = new Location();
  List<double> result=[];

  var loc = await location.getLocation();
  result.add(loc.latitude);
  result.add(loc.longitude);
  result.add(4213);
  return result;
}

答案 1 :(得分:0)

原因是您对所有按钮和模式元素使用相同的ID,因此在执行绑定操作时,document.getElementById()仅对第一个起作用。

我根据您要解决的代码创建了codepen。请检查一下。这个想法是为每个元素创建唯一的ID。它们在处理事件时的关系基于它们的相应索引。

(function(window, document, $, undefined) {
  'use strict';
  
  var data,
      source,
      template;
  
  // Our data object
  data = {"products": 
[{
  "id": 0, 
   "name": "Ocean Blue Shirt",
   "description": "<p>Ocean blue cotton shirt with a narrow collar and buttons down the front and long sleeves. Comfortable fit and tiled kalidoscope patterns. </p>", 
   "category": "men", 
   "image_url": "https://burst.shopifycdn.com/photos/young-man-in-bright-fashion_925x.jpg", 
   "unit_cost": 92.95, 
   "inventory": 0
},  

 {"id": 1, 
  "name": "Classic Varsity Top",
  "description": "<p>Womens casual</p>",
  "category": "women", 
   "image_url": "https://burst.shopifycdn.com/photos/young-man-in-bright-fashion_925x.jpg", 
   "unit_cost": 80.00, 
   "inventory": 0}
 ]};
  
  // Get the template source
  source = $("#my-template").html();
	  
  // Compile the template into a Handlebars function
  template = Handlebars.compile(source);
	
  // Pass our data object to the compiled Handlebars function
  // Insert back into the page
	$('#welcome-message').html(template(data));
 //binding events for elements
  var $openEls = document.getElementsByClassName('open');
  for(var i =0 ; i< $openEls.length; i++){
    var $open = $openEls[i];
    $open.onclick = function(){
      var index = this.id.split('-')[1];
      // console.log('open index ', index)
      var modal = document.getElementById("myModal-"+index);
      modal.style.display = 'block';
    }
  } 
  
  var $closeEls = document.getElementsByClassName('close');
  for(var j =0 ; j< $closeEls.length; j++){
    var $close = $closeEls[j];
    $close.onclick = function(){
      var closeIndex = this.id.split('-')[1];
      // console.log('close index ', closeIndex)
      var modal = document.getElementById("myModal-"+closeIndex);
      modal.style.display = 'none'; 
    }
  }
})(window, document, jQuery);
<div id="welcome-message">
  <script id="my-template" type="text/x-handlebars-template">
    {{#each products}}

    <tr>

      <td>

        <!-- Trigger/Open The Modal -->
        <button id="myBtn-{{@index}}" class="open">{{name}}</button>

        <!-- The Modal -->
        <div class="modal" id="myModal-{{@index}}">
          <!-- Modal content -->
          <div class="modal-content">
            <span class="close" id="close-{{@index}}">&times;</span>
            <li>Product Description: {{{description}}}</li>
          </div>
        </div>
      </td>
      <td>
        ${{unit_cost}}
      </td>
    </tr>
    {{/each}}

  </script>
</div>

您可以按照以下图片进行操作

enter image description here