如何使这个jQuery对象脚本更容易?

时间:2017-09-15 20:42:24

标签: javascript jquery

我开始意识到如果我开始在该对象中添加更多不同的东西,我将不得不添加更多代码

它所说的output += element.item + '<br>' + element.cost + '<br>';

那么我该如何制作这个代码,而不必在我想要添加到该对象输出的那个区域输入额外的代码?

我知道有一种方法,你不必每次都为这个区域输入额外的代码,例如我是否会另外添加这个(element.events等)。我将不得不键入更多该区域的附加代码将花费更多时间并且看起来像我试图避免的那样。

element.item + '<br>' + element.cost + '<br>' + element.events + '<br>';

等......所以我需要一个新的解决方案,以便代码可以自动输出所有对象的内容,所以我不必输入新的附加代码,它说的是

output += element.item + '<br>' + element.cost + '<br>';

下面&#39;我的代码,我正在谈论。

&#13;
&#13;
var data = {
  shop: [{
      item: "Ps3",
      cost: "$150"
    },
    {
      item: "xbox 360",
      cost: "$140"
    }
  ]
};
$(document).ready(function() {
  var z = $('.z'); // Grab class z to toggle
  var x = $('#x');
  var output = '';
  $.each(data.shop, function(index, element) {
    output += element.item + '<br>' + element.cost + '<br>';
  });
  x.html(output);
  $("button").click(function() {
    z.toggle(); // Toggle z on button click
  });
});
&#13;
h1 {
  color: gold;
}

#x {
  color: white;
  text-align: center;
}
.z {
  background-color: red;
  width: 250px;
  margin: auto;
  padding-bottom: 5px;
  display: none;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="z">
<h1>Details </h1>
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

你想要这样的东西吗?

我所做的是循环遍历elementdata.shop变量的所有键,因此我只需在元素的每个值中添加<br>标记。它的通用性将完成工作!

&#13;
&#13;
var data = {
  shop: [{
      item: "Ps3",
      cost: "$150"
    },
    {
      item: "xbox 360",
      cost: "$140"
    }
  ]
};
$(document).ready(function() {
  var z = $('.z'); // Grab class z to toggle
  var x = $('#x');
  var output = '';
  $.each(data.shop, function(index, element) {
    for(var j in element){
      output += element[j] + '<br>' ;
    }
  });
  x.html(output);
  $("button").click(function() {
    z.toggle(); // Toggle z on button click
  });
});
&#13;
h1 {
  color: gold;
}

#x {
  color: white;
  text-align: center;
}
.z {
  background-color: red;
  width: 250px;
  margin: auto;
  padding-bottom: 5px;
  display: none;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="z">
<h1>Details </h1>
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>
</html>
&#13;
&#13;
&#13;

相关问题