这是我的表单:
<div class="mutiple-array-form">
<?php $form = ActiveForm::begin(); ?>
<table id="sampleTbl", class="table table-striped table-bordered">
<thead>
<tr id="myRow">
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>william</td>
<td>32</td>
</tr>
<tr>
<td>Muli</td>
<td>25</td>
</tr>
<tr>
<td>Sukoco</td>
<td>29</td>
</tr>
</tbody>
</table>
<div class="form-group">
<?= Html::button('Create',['class' => 'btn btn-success _addNew', 'onclick' => 'myfunction()']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
下面是我的Javascript代码:
<?php
$script = <<< JS
function myfunction() {
alert(document.getElementById("sampleTbl").rows.namedItem("myRow").innerHTML);
}
JS;
$this->registerJs($script);
?>
我的代码不工作。当我点击按钮时,什么也没发生。例如,我想在alert中使用array显示表值。请帮助!
你所尝试的将不起作用,因为在yii2中以某种方式声明内联脚本中的函数不起作用,我不知道它的正确原因,我正在努力寻找原因。
现在你的代码将工作,如果你写你的脚本像这样
<?php
$script = <<< JS
$('#idOfButton').click(function(){
alert(document.getElementById("sampleTbl").rows.namedItem("myRow").innerHTML);
});
JS;
$this->registerJs($script);
?>
它只会打印页眉
的值现在,如果您希望将表中的数据作为数组并警告它,请尝试下面的代码
<?php
$script = <<< JS
$('#idOfButton').click(function(){
var myTableArray = [];
$("table#sampleTbl tr").each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).text());
});
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
});
JS;
$this->registerJs($script);
?>
我建议你使用AppBundle
来使用脚本,这样你就可以通过浏览器调试代码并自己找出问题,这将帮助你找到答案。