duanbo1659 2016-12-29 15:59
浏览 18
已采纳

使用JQuery将行附加到表中

I'm trying to append table row from inputs.

<script type="text/javascript">
    function addDrug(){
        var start = $('<tr>');
        var end = $('</tr>');

        var add_DrugsCurrentlyUsed = $('#add_DrugsCurrentlyUsed').val();
        var add_SourceOfDrugs = $('#add_SourceOfDrugs').val();
        var add_FrequencyOfUse = $('#add_FrequencyOfUse').val();
        var add_ModeOfDrugUse = $('#add_ModeOfDrugUse').val();

        var td_DrugsCurrentlyUsed =$('<td>'+add_DrugsCurrentlyUsed+'</td>');
        var td_SourceOfDrugs =$('<td>'+td_SourceOfDrugs+'</td>');
        var td_FrequencyOfUse =$('<td>'+td_FrequencyOfUse+'</td>');
        var td_ModeOfDrugUse =$('<td>'+td_ModeOfDrugUse+'</td>');

        $('#drugTable').append(start+td_DrugsCurrentlyUsed+td_SourceOfDrugs+td_FrequencyOfUse+td_ModeOfDrugUse+end);
    };
</script>

But when I append it, it shows something like

object Object][object Object][object Object][object Object][object Object][object Object]

into the table.

  • 写回答

5条回答 默认 最新

  • dongpi9494 2016-12-29 16:11
    关注

    You have a few issues, for example you are trying to add an end tag, which isn't how the DOM works. The DOM doesn't have the concept of ending tags, so there's no point to insert one. Just insert the <tr> element and add children to it.

    You are also using the + operator to try to concatenate objects, which results in the string [object Object] when an object is converted to a string for concatenation. You shouldn't be trying to add them together; just replace the + operators with commas (,) and your code will somewhat work.

    Better yet, you can restructure the code to be a bit more fool-proof against values that contain HTML special characters, while also more clearly expressing what you are trying to do (and making it easier to add more columns later).

    function addDrug() {
        $('#drugTable').append(
            $('<tr>').append(
                [
                    '#add_DrugsCurrentlyUsed',
                    '#add_SourceOfDrugs',
                    '#add_FrequencyOfUse',
                    '#add_ModeOfDrugUse',
                ].map(function (id) {
                    return $('<td>').text($(id).val());
                })
            )
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)