1。jQuery每个函数(键,值)的结果仅返回最后一个键和值。 2.在警报框中工作正常 3.在将数据转换为HTML时,它仅返回最后一个键和值
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
$.each($.parseJSON(result), function(k, v) {
console.log(k + ' is ' + v);
$('#stage').html('<p>' + k +':' + v+ '</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="stage" style = "background-color:#cc0;">
STAGE
</div>
我不知道如何获取HTML中的所有值,请提前帮助。
答案 0 :(得分:1)
因为在每个循环中都在#stage
上重写了html。您需要将内容存储在变量中,并在循环结束后,将resutl插入文档中。
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
var html = "";
$.each($.parseJSON(result), function(k, v) {
html += '<p>' + k +':' + v+ '</p>';
});
$('#stage').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="stage" style = "background-color:#cc0;">
STAGE
</div>
答案 1 :(得分:1)
您也可以使用.append()
代替.html()
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
$.each($.parseJSON(result), function(k, v) {
//console.log(k + ' is ' + v);
$('#stage').append('<p>' + k + ':' + v + '</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="stage" style="background-color:#cc0;">
STAGE
</div>