在onclick函数中发送数组

时间:2018-05-15 18:24:44

标签: javascript jquery

function show(array){
  console.log(array);
}

function main() {
  var send = ["HOLA", "ADIOS"];
  $('#table').append('<tr>'+
                    '<td style="width: 35%">Oscar</td>'+
                    '<td style="width: 6%">'+
                        '<button type="button" class="btn btn-success" data-dismiss="modal" onclick=show('+send+')>+</button>'+
                    '</td>'+
                '</tr>'
   );
}
main();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" class="table table-bordered">
	<thead>
		<tr>
		  <th style="width: 35%" id="wallet-modal-table-name-header"></th>
			<th style="width: 6%"  id="wallet-modal-table-options-header"></th>
		</tr>
	</thead>
</table>

我有这个代码,我想发送数组“发送”但是当我在函数中将它作为参数发送时,它会向我显示错误。我该怎么办?

2 个答案:

答案 0 :(得分:1)

对于动态创建的元素,请使用事件委派方法:

$(selector4parent).on(event, selector4children, handler);

&#13;
&#13;
function show(array) {
  console.log(array);
}

function main() {
  $('#table').on('click', '[type="button"]', function(e) {
    var send = ["HOLA", "ADIOS"];
    show(send);
  });


  $('#table').append('<tr>' +
    '<td style="width: 35%">Oscar</td>' +
    '<td style="width: 6%">' +
    '<button type="button" class="btn btn-success" data-dismiss="modal">+</button>' +
    '</td>' +
    '</tr>'
  );
}
main();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table" class="table table-bordered">
  <thead>
    <tr>
      <th style="width: 35%" id="wallet-modal-table-name-header"></th>
      <th style="width: 6%" id="wallet-modal-table-options-header"></th>
    </tr>
  </thead>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以在字符串之外创建按钮,然后将其附加到您希望的TD中。

var $btn = $(document.createElement("BUTTON"));
$btn.attr({ 'type': 'button', 'data-dismiss': 'modal'}).addClass('btn btn-success');

$btn.click(function()
{
    show(send);
});

$('td-selector').append($btn);