【问题标题】:create jquery components using a function and using them in the HTML使用函数创建 jquery 组件并在 HTML 中使用它们
【发布时间】:2018-08-01 02:56:54
【问题描述】:

我想使用一个函数创建一些 jquery 组件并在 html 中使用它们,但不知道该怎么做。这是我尝试过的。

function CreateElement (id, type) {
    $(document).ready (function () {
        if (type == "metricCombobox") {
            var element = $('#' + id).combobox();

            return element;
        }
    });    
}

在 HTML 页面中。

<select id="' + CreateElement('metricComboboxSimples', 'metricCombobox') + '" >

【问题讨论】:

    标签: javascript jquery html components


    【解决方案1】:

     您真的需要在 DOM 中创建元素,然后将内容附加到它吗? 或者你可以在 jQuery 中创建所有元素吗?至少对我来说,在 jQuery 中创建更容易理解,您可以控制元素的整个创建,然后将其附加到已经在 DOM 中的另一个元素,甚至附加到 document.body... 请采取查看下面的代码并运行 sn-p 看看我的回答是否对您有帮助。

    var selectOptions= [
          {val : 1, text: 'One'},
          {val : 2, text: 'Two'},
          {val : 3, text: 'Three'}
    ];
    
        function CreateElement (id, type, options) {
            $(document).ready (function () {
    
                if (type == "metricCombobox") {
                    var arr = options;
                    var element = $('<select>');
                    element.attr('id', id); 
    
                    $(arr).each(function() {
                     var selOption = $("<option>");
                     selOption.attr('value', this.val);
                     selOption.text(this.text);
                     element.append(selOption);
                    });
                    
                }else if (type == 'input'){
                    var element = document.createElement('input');
                    element.value = 'input created'
                    $(element).attr('id',id);
                }
    
                $("#MyDiv").append(element);
            });    
        }
    
        CreateElement('metricComboboxSimples', 'metricCombobox', selectOptions);
        CreateElement('testeId', 'input');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div id="MyDiv"></div>

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多