首页 > 解决方案 > 通过 JavaScript 复制具有值的表单

问题描述

我在 php 文件中有一个表单,我想添加表单的副本以及 JavaScript 的值。

<div class="form-group">
    <div class="col-sm-12">
        <div class="input-group">
            <div class="input-group-addon"><?php _e('Taxonomy', 'textdomain'); ?></div>
            <div class="select">
                <select name="categoryxpath_tax" id="select-taxonomy-type" class="form-control" ng-model="model.categoryxpath_tax">
                    <option value=""><?php _e('Please select a taxonomy', 'textdomain'); ?></option>
                    <?php
                    if (get_post_meta($post_object->ID, 'sc_post_type', true) == "") {
                        $taxonomies = get_object_taxonomies('post', 'objects');
                    } else {
                        $taxonomies = get_object_taxonomies(get_post_meta($post_object->ID, 'sc_post_type', true), 'objects');
                    }
                    foreach ($taxonomies as $taxonomy) { ?>
                    <option value="<?php echo $taxonomy->name; ?>"><?php echo $taxonomy->labels->name; ?></option>
                    <?php } ?>
                </select>
            </div>
        </div>  
    </div>
</div>

我通过 JavaScript 添加了表单,但无法获取 foreach 循环中的值:

if (type == 'taxonomy_field') {
    var taxonomy_value = document.getElementById('select-taxonomy-type');
    var taxonomy_field_name = taxonomy_value.options[taxonomy_value.selectedIndex].text;
    var taxonomy_field_value = taxonomy_value.options[taxonomy_value.selectedIndex].value;
    $($event.target).closest('.form-group').before($compile(
        '<div class="form-group">' +
            '<div class="col-sm-12">' +                         
                '<div class="input-group">' +
                    '<div class="input-group-addon">' + translate.Taxonomy + '</div>' +
                    '<div class="select">' +
                        '<select name="categoryxpath_tax" class="form-control">' +
                            '<option value="">' + translate.Please_select_a_taxonomy + '</option>' +
                            '<option value="' + taxonomy_field_value + '">' + taxonomy_field_name + '</option>' +
                        '</select>' +   
                    '</div>' +  
                    '<span class="input-group-btn"><button type="button" class="btn btn-primary btn-block" ng-click="remove_field($event)"><i class="icon ion-trash-a"></i></button></span>' +
                '</div>' +
            '</div>' +  
        '</div>'
    )($scope));
}

我怎样才能做到这一点?

标签: javascriptphpwordpress

解决方案


cloneNode()是您正在寻找的。

const clonedForm = document.querySelector("form").cloneNode(true); document.querySelector("#someOtherElement").appendChild(clonedForm); 并且不要使用内联 PHP,这是不好的做法。


推荐阅读