JQuery动态添加按钮,文本不在按钮中

时间:2016-08-09 20:02:00

标签: javascript jquery

当我尝试从jQuery创建按钮时,文本显示在我创建的按钮元素之外。我已经尝试单独创建每个按钮并作为一个组,这两种方法似乎都不起作用。我做错了什么?

<div id = 'output_div'></div>

var main = function(){
    var selections = ['derp', 'herp', 'merp', 'foo'];


    //individually creating each button
    for(var i = 0; i < selections.length; i++){
        $('#output_div').append("<input type='button'>" + selections[i] +
          "</input>");
    };

    $('#output_div').append('<br><br>');


    //buttons all created at the same time
    var group_buttons = '';

    for(var i = 0; i < selections.length; i++){
        group_buttons += ("<input type='button'>" + selections[i] + "</input>");
    };

    $('#output_div').append(group_buttons);
};

$(document).ready(main);

https://jsfiddle.net/fjr56Lsj/4/

4 个答案:

答案 0 :(得分:2)

使用jquery创建按钮的另一种方法如下:

var dynamicButton = $('<button/>', {
    text: selections[i],
    id: 'dynamicButton_'+i
});
$('#output_div').append(dynamicButton);

答案 1 :(得分:1)

作为输入类型按钮属性,使用value = selections [i](小心保留Ur引号),否则使用button标签代替输入元素

答案 2 :(得分:1)

将按钮文字设置为value <input>属性,或将按钮渲染为<button> :< / p>

$(function() {
  var selections = ['derp', 'herp', 'merp', 'foo'];

  for (var i = 0; i < selections.length; i++) {
    $('#output_div').append("<input type='button' value='" + selections[i] + "' />");
  };

  $('#output_div').append('<br><br>');

  for (var i = 0; i < selections.length; i++) {
    $('#output_div').append("<button>" + selections[i] + "</button>");
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'></div>

答案 3 :(得分:1)

按钮也可以这种方式创建:

$('<button/>', {
    text: selections[i]
 })

var main = function() {
  var selections = ['derp', 'herp', 'merp', 'foo'];


  //individually creating each button
  for (var i = 0; i < selections.length; i++) {

    $('#output_div').append($('<button/>', {
      text: selections[i]
    }));
  };

  $('#output_div').append('<br><br>');
};

$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output_div'>

</div>