点击事件的jquery格式化输出

时间:2018-04-04 11:53:56

标签: javascript jquery html events web

我有这段代码所以当我点击按钮时,一些json数组加载使用jquery这样的东西

Adobe Creative Cloud for Enterprise (Mac)

然后我的外出是完全错误的输出像这样

$("#clickmetoload").click(function()
  {
    $('#id').append("<span class=\"id\">"+received.id+"<span  class=\"name\">"+received.name+"</span></span>");
  });

但我希望它像这样输出

1 2 3 admin user1 user2

2 个答案:

答案 0 :(得分:0)

首先,您错过了span结束标记,这是该显示的原因 如果你想换行,你应该在行尾添加<br>

这是一个例子

&#13;
&#13;
received = {}
received.id = 0
received.name = "admin"
$("#clickmetoload").click(function() {
  $('#id').append("<span class=\"id\">" + received.id + " </span><span  class=\"name\">" + received.name + "</span><br>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="clickmetoload" value="clickmetoload">clickmetoload</button>
<p id="id"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码一般都很好。您只需要一些css以多行显示它。只需在外部display: block;上使用span! ;)

&#13;
&#13;
var data = [
  {id: 1, name: 'admin'},
  {id: 2, name: 'user1'},
  {id: 4, name: 'user2'}
];

$("#clickmetoload").click(function() {
    data.forEach(function(received) {
        $('#id').append("<span class=\"id\">"+received.id+" <span class=\"name\">"+received.name+"</span></span>");
    });
});
&#13;
span.id {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickmetoload">click me to load</button>
<div id="id"></div>
&#13;
&#13;
&#13;