【问题标题】:how to get array of table after click button in YII2在YII2中单击按钮后如何获取表格数组
【发布时间】:2016-01-20 16:03:50
【问题描述】:

这是我的表格:

<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);
?>

我的代码不起作用。当我单击按钮时,没有任何反应。例如,我想在警报中使用数组显示表值。请帮忙!

【问题讨论】:

  • 你检查了你的渲染文件,其中添加了你的 js 文件。这是正确的地方吗

标签: javascript php arrays yii2


【解决方案1】:

你正在尝试的将不起作用,因为在 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 使用脚本,这样您就可以通过浏览器调试代码并自己找出问题,这将帮助您找到答案。

【讨论】:

  • 感谢您的关注,它的工作。下一个问题,我想保存在我的数据库中。如何编码 Json 这个数组然后发送到我的控制器解码 Json 然后保存它? @MikeRoss
  • @stfvns 看到这个方法JSON.stringify(yourArray) 它会将你的数组转换为JSON
猜你喜欢
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2011-01-06
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多