繁体   English   中英

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

[英]How can I make this jQuery object script easier?

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

它说的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>';

这是我正在谈论的代码。

 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 }); }); 
 h1 { color: gold; } #x { color: white; text-align: center; } .z { background-color: red; width: 250px; margin: auto; padding-bottom: 5px; display: none; } 
 <!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> 

你想要这样的东西吗?

我要做的是遍历data.shopelement变量的所有键,因此我将向每个元素值添加一个<br>标记。 它的通用性将完成工作!

 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 }); }); 
 h1 { color: gold; } #x { color: white; text-align: center; } .z { background-color: red; width: 250px; margin: auto; padding-bottom: 5px; display: none; } 
 <!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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM