如何在每个循环迭代中附加一个按钮?

时间:2017-01-28 14:21:37

标签: javascript jquery

我有一个数组,arr。我想为#enquirieswall为数组中的每个对象添加按钮。我尝试了各种方法,但到目前为止还没有。这是我到目前为止所提出的:

<script>
var arr = [{"userid": "jim", "title":"help"}, {"userid": "pim", "title":"hello"}]  

var i;
$("enquirieswall").empty();
for (i=0; i < arr.length; i++){
  var a = document.createElement("a");
  a.setAttribute("href","#");
  a.setAttribute("class","ui-btn");
  //added according to comments on my question
  a.textContent = arr[i].title;
  a.setAttribute("onclick", "window.location='enquiriesdetails.php?userid=" + arr[i].userid +"'");  
  $("#enquirieswall").append(a);
}
</script>

<div id="enquirieswall"></div>

目前结果是彼此并排的链接,我希望它们在按钮中。

1 个答案:

答案 0 :(得分:0)

将createElement更改为button,将ui-btn更改为btn

for (i = 0; i < arr.length; i++) {
                      var a = document.createElement("button");
                      a.setAttribute("href", "#");
                      //a.textContent = arr[i].title;
                      a.innerHTML = arr[i].title.toString();
                      a.setAttribute("class", "btn");
                      a.setAttribute("type", "button");
                      a.setAttribute("onclick", "window.location='enquiriesdetails.php?userid=" + arr[i].userid + "'");
                      $("#enquirieswall").append(a);
                    }