简体   繁体   English

使用jQuery中的选项创建选择DOM对象,传递属性

[英]Create select DOM object with options in jQuery, Passing Attributes

How can I create a select DOM object with options in jquery similar to this input creation example? 如何在jquery中使用此输入创建示例来创建带有选项的select DOM对象?

$('<input />', {
  name: 'age',
  type: 'number',
  placeholder: 'enter a number 1'
}).appendTo('#app');

Is there a way to create it passing attributes? 有没有一种创建传递属性的方法?

You can create just by passing the entire select with option as string 您可以通过将带有选项的整个select传递为字符串来创建

$('<select name="number">' +
  '<option>1</option>' +
  '<option>2</option>' +
  '<option>3</option>' +
'</select>').appendTo('body');

Another solution, using an array of objects having the required value and text and creating new select element based on the array information. 另一种解决方案是使用具有所需valuetext的对象数组,并根据数组信息创建新的选择元素。

 $(document).ready(function () { var arrSelect = [ { value: 1, text: 'One' }, { value: 2, text: 'Two' }, { value: 3, text: 'Three' } ]; var select = $('<select>').appendTo('body'); //Create new select element //Loop through the array of objects and then create new option and append to select element arrSelect.map(function (arr) { select.append($("<option>").attr('value', arr.value).text(arr.text)) }); $("body").append(select); //Append select to body element }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 

When creating an element with jQuery, any attribute, or even jQuery method, can be used in the options object, so you can do 使用jQuery创建元素时,可以在options对象中使用任何属性甚至jQuery方法,因此您可以执行

 $('<select />', { name : 'test', on : { change : function() { /* stuff */ } }, append : [ $('<option />', {value : "1", text : "Opt 1"}), $('<option />', {value : "2", text : "Opt 2"}), $('<option />', {value : "3", text : "Opt 3"}) ] }).appendTo('#app'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div> 

1_ you can select Multiple DOM Multi DOM Select 1_您可以选择多个DOM Multi DOM Select

like so : 像这样:

$( "div, .sCLASS, p.myClass" ).whatever...

2_ you can also select Single DOM with concate Single DOM Select 2_您也可以选择“单个DOM”并连接“ Single DOM Select

like so : 像这样:

$( "p" + ".sCLASS" ).whatever...

BUT you can't pass arg with it 但是你不能通过它

The object select is created and then the options objects are appended. 创建对象选择,然后附加选项对象。

$('<select />', {
  id: 'my-numbers',
  name: 'select-number'
})
.append($("<option/>", {
    value: '1',
    text: 'number1'
}))
.append($("<option/>", {
    value: '2',
    text: 'number2'
}))
.appendTo('#app');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM