javaScript从表单中收集信息

时间:2014-08-27 01:58:05

标签: javascript html css

我正在尝试创建一个表单来收集信息并将其添加到现有对象中。任何反馈都会有所帮助。这是我到目前为止所拥有的。感谢您抽出宝贵时间阅读这篇文章。

以下是相关信息:

data = [
  { name: "Mark-Paul Gosselaar", photo_url: "" },
  { name: "Delta Burke", photo_url: "img/avatars/delta.png" },
  { name: "Alf", photo_url: "img/avatars/alf.png" },
  { name: "Jaleel White", photo_url: "img/avatars/jaleel.png" },
  { name: "Ralph Macchio", photo_url: "img/avatars/ralph.png" },
  { name: "Candace Cameron", photo_url: "img/avatars/candace.png" },
  { name: "Patrick Duffy", photo_url: "img/avatars/pduff.png" },
  { name: "Arnold Schwartzengger", photo_url: "img/avatars/arnold.png" }
];

我的索引页

<!DOCTYPE html>
 <html>
  <head>
   <link href="css/application.css" rel="stylesheet">
   <script src="js/vendor/jquery.min.js" type="text/javascript"></script>
   <script src="js/vendor/underscore.js" type="text/javascript"></script>
   <script src="js/application.js" type="text/javascript"></script>
 </head>

<div id="main-content">
  <!-- The page width is 817px -->
  <!-- Example of using the form CSS to help you out. -->
  <form>
    <div>
      <label>Full Name</label>
      <input name="name" type="text" required />
    </div>
    <div>
      <label>Photo URL</label>
      <input name="photo_url" />
    </div>
    <button type="submit">Create</button>
  </form>

  <hr />

  <!-- Employee list goes here. There is initial data for you in application.js -->
  <script>
    $( document ).ready(function() {
     var html = "";
       for( i=0; i<data.length; i++ ) {
          //create the image div
       html = "<div id=\"image_container" + i + "\"><img src=\"" + data[i].photo_url + "\"></div>";
       //create the name div
       html += "<div id=\"inner_container" + i + "\">" + data[i].name + "</div>";
      //append the divs to the body
       $("body").append(html);
      //add click event to each image div
      $("#image_container"+i).click(function() {
      alert( $(this).attr('id') );
       });
      }
     });
    </script>

       </div>
     </body>
  </html>

2 个答案:

答案 0 :(得分:1)

"\" "\""的错误也应该是 html = "<div id=\"image_container" + i + "\"><img src=\"" + data[i].photo_url + "\"></div>"; html += "<div id=\"inner_container" + i + "\">" + data[i].name + "</div>";

{{1}}

答案 1 :(得分:0)

只有在您的代码中需要更改才能在使用html()方法之前使用append()。见下文:

....
var $tempVar = $($.parseHTML(html));  
//append the divs to the body
$("body").append($tempVar);
//add click event to each image div
$("#image_container"+i).click(function() {
alert( $(this).attr('id') );
....

请参阅here以了解html和追加方法之间的区别。